-
Notifications
You must be signed in to change notification settings - Fork 21
Description
If we have this function
def f(to: TraversableOnce[Char]) {}and an optional string
val optionalString = Some("Hello")and try to pass the result of 'Option.getOrElse' to the function
f(optionalString.getOrElse("<none>"))we get this error message:
type mismatch; found: java.lang.Comparable[java.lang.String] required: TraversableOnce[Char]This is a bit misleading.
The definition of Option.getOrElse is:
sealed abstract class Option[+A] ... {
def getOrElse[B >: A](default: => B): B
...
} By passing 'getOrElse' to 'f' the type 'B' must be a super type of 'String' and a subtype of 'TraversableOnce[Char]'. No such type exist but the closest is 'Comparable[String]'. This leaks into the error message which then becomes misleading.
A better error message would inform the programmer that "no type B could be found that is a super type of String and a subtype of TraversableOnce[Char]" or something along these lines.
By the way, forcing the type B to String
f(optionalString.getOrElse[String]("<none>"))makes the code compile. Now, getOrElse's result is a String and an implicit conversion to StringOps can kick in to make String compatible with TraversableOnce[Char].