I am looking at scala in action book and it has this code
sealed abstract class Maybe[+A] {
def isEmpty: Boolean
def get: A
def getOrElse[B >: A](
In Scala you cannot have covariant types in method parameters.
This is because allowing covariant types in method parameters breaks type safety.
In order to have a covariant type you must use a bounded type:
getOrElse[B >: A](default: B): B
This says find some type, B
, such that it is a superclass of A
and that becomes the method return type.
In your case A
is Int
and you pass in a String
. The only type B
which is a superclass of both Int
and String
is Any
.
In this case B
becomes Any
so the method returns Any
.