The preference `contains [BB>: B] (e: BB): Boolean` instead of` contains (e: Any): Boolean`

What is the advantage of defining contains

like contains[BB >: B](e: BB): Boolean

instead contains(e: Any): Boolean

in Scala.

Either.contains

the Scala standard library uses the first signature and I don't understand why such a signature is in the second signature.

+3


source to share


1 answer


In this case, no: the two signatures are equivalent. But it does ensure consistency with the signatures of other members such as

 getOrElse[BB >: B](or: ⇒ BB): BB

      

There is a difference for them because it BB

is part of the return type, so if we pass B

, we get B

back, which we wouldn't have with getOrElse(or: => Any): Any

.



What amazes me is why would you ever want to pass something that is not B to this function

You wouldn't. But contains(e: B)

would not be allowed to Either

be covariant. Try it, the compiler will reject it on the grounds that it B

appears in a contravariant position. Covariance means that, for example, Either[A, SubtypeOfFoo]

is a subtype Either[A, Foo]

. Therefore, any challenge that is legal for Either[A, Foo]

must also be legal for Either[A, SubtypeOfFoo]

, and that includes contains(Foo)

.

+3


source







All Articles