Skip to content

Misleading error message when type bound cannot be satisfied  #4667

@scabug

Description

@scabug

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions