Why does the "contain" method in "Option" use the second type with a lower border instead of the "Any" type?

I was looking at the Option class in Scala and came across a contains method:

final def contains[A1 >: A](elem: A1): Boolean 

The option is covariant, so I understand that it cannot just use A as an elem type. However, given that type A1 is never used, why the method cannot be like this:

 final def contains(elem: Any): Boolean 

Is it just a style or am I missing something important?

+7
scala
source share
2 answers

No reason, it's just an oversight. In fact, this is not even the only one. Either.joinRight , for example, also contains unnecessary lower bounds. But since their removal will mean a break in the initial and binary compatibility, this has not yet happened.

+3
source share

This is directly related to the fact that Option covariant and is actually required in order for the types to match.

 class Foo(x: Int) object Bar entends Foo(0) def foo(t: Option[Foo]) = t contains (new Foo(2)) 

I can actually pass in the type Option[Bar.type] , and it will "work" because Bar is Foo , and the type of type constraint requires that it also accept types that are supertypes of parameterized type A

 val res = foo(Some(Bar)) >> res0: Boolean = false 

Note that the above actually calls contains in the instance of a Option[Bar.type] . Therefore, [A1 >: A] .

+2
source share

All Articles