Scala: variance type 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 numbers come out in 2.8) and I was 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 what i can only do

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

      

Of course, I know that when declaring a function the way it has been declared that a type _2

can inherit from a type _1

, "A" can be a generic trait, or so on. I know this means that the compiler must 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 do the double declaration _1:Int, _2:int

?

+2


a source to share


2 answers


I may be misunderstanding you, but if you just want both parameters to be the same, you can do something like the following:

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

      



This indicates that it B

is a bottom and top type, constrained A

, so it should be A

. Thus, it will only compile if _1

and _2

are of the same type.

+1


a source


I will use overloading instead.



+2


a source







All Articles