Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the "contains" method on "Option" use a second type with lower bound instead of an "Any" type?

Tags:

scala

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?

like image 363
Boomah Avatar asked Feb 13 '15 14:02

Boomah


2 Answers

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.

like image 191
kiritsuku Avatar answered Nov 19 '22 11:11

kiritsuku


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].

like image 28
wheaties Avatar answered Nov 19 '22 10:11

wheaties