I was looking through the Option class in Scala and and came across the contains method:
final def contains[A1 >: A](elem: A1): Boolean
Option is covariant so I understand that it can't just use A as the type of elem. However, given that the type A1 is never used, why can't the method just be this:
final def contains(elem: Any): Boolean
Is it just a style thing or have I missed something important?
There is no reason, it is just an oversight. Actually, it is not even the only one. Either.joinRight
for example also contains unnecessary lower bounds. But because removing them would mean to break source and binary compatibility it didn't happen so far.
It is directly related to the fact that Option
is covariant and in fact, required in order for the types to match up.
class Foo(x: Int)
object Bar entends Foo(0)
def foo(t: Option[Foo]) = t contains (new Foo(2))
I can actually pass in a type of Option[Bar.type]
and it will "work" because Bar
is a Foo
and type boundedness of the type requires that it also accept types that are super types of the parameterized type A
.
val res = foo(Some(Bar))
>> res0: Boolean = false
Note that the above is actually calling contains
on an instance of a Option[Bar.type]
. Hence, the [A1 >: A]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With