views:

99

answers:

2

I was playing around the other day with making a class to handle some arithmetic operations (yes, I know numeric is coming out in 2.8) and found myself wondering how to simplify the following:

def Foo[A]( _1:A, _2:A ) = (_1, _2) match{
    case _1:Bar, _2:Bar => _1 + _2
    case _1:Baff, _2:Baff => _1 push _2
    case _, _ => None
}

so that I can do just

def Foo[A]( _1:A, _2:A ) = _1 match{
    case _1:Bar => _1 + _2
    case _1:Baff => _1 push _2
    case _ => None
}

Granted, I know that in declaring the function the way it's been declared that _2's type could conceivably inherit from _1's type, "A" could be a shared trait, or so on. I know this means the compiler needs to protest to protect the code. Is there a way to say "I want _1 and _2 to be the same extact class" so that I don't have to make the double _1:Int, _2:int declaration?

+1  A: 

Perhaps Im misunderstanding you, but if you just want the two parameters to be required to be the same type, you can do something like the following:

def Foo[A,B >: A <: A](_1: A, _2:B) = ...

This specifies that B is both lower and upper type bounded by A, thus must be A. Thus it will only compile if _1 and _2 are of the same type.

Jackson Davis
I got home to try this out and it doesn't work. It doesn't even compile. It fails at the "+" if there's more than an overloaded method. This something that will compile in 2.8?
wheaties
I tried it on 2.7.7, but It should work on 2.8. What error are you getting?
Jackson Davis
+2  A: 

I'd use overloading here instead.

Daniel