Scala: type variance and pattern matching between two equal types
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?
I'd use overloading here instead.
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.
精彩评论