softshipper
softshipper

Reputation: 34119

Why type any is returned?

I have following ADT

sealed trait Option[+A] {

  def map[B](f: A => B): Option[B] = this match {
    case None => None
    case Some(a) => Some(f(a))
  }

  def getOrElse[B>:A](default: => B): B = this match {
    case None => default
    case Some(a) => a
  }

}

case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]

I've play a bit with the getOrElse function:

scala> Some(4).getOrElse(44)
res1: Int = 4

scala> Some(4).getOrElse("Hello")
res2: Any = 4

Why the last return the Any type?

Upvotes: 1

Views: 43

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45836

You've said B must be a super type of A.

In the first example, both A and B are ints, so there's no problem.

In the second example, you have String and ints. The only super type of int that satisfies your constraint [B>:A] is Any.

Think about it like this: what type did you expect it would return? You have an int type defaulting to a String type. The type must be Any for that to be possible.

Upvotes: 4

Related Questions