Skip to content

Inconsistent behavior of the compiler for ambiguous implicit views implemented as vals or defs #6316

@scabug

Description

@scabug

When defining a ambiguous implicit view, the compiler will complain for an implicit def, but not for an implicit val:

scala> implicit val impl: String => Int = (s: String) => s.toInt
impl: String => Int = <function1>

scala> "2" - 1
java.lang.StackOverflowError
	at $anonfun$1.apply(<console>:9)
scala> implicit def stringToInt(s: String): Int = s.toInt
<console>:7: error: type mismatch;
 found   : s.type (with underlying type String)
 required: ?{def toInt: ?}
 possible cause: missing arguments for method or constructor
Note that implicit conversions are not applicable because they are ambiguous:
 both method augmentString in object Predef of type (x: String)scala.collection.immutable.StringOps
 and method stringToInt of type (s: String)Int
 are possible conversion functions from s.type to ?{def toInt: ?}
       implicit def stringToInt(s: String): Int = s.toInt

Further the implicit view is not ambiguous if the type annotation on the val or def is omitted:

scala> implicit val impl = (s: String) => s.toInt
impl: String => Int = <function1>

scala> "2" - 1
res0: Int = 1
scala> implicit def stringToInt(s: String) = s.toInt
stringToInt: (s: String)Int

scala> "2" - 1
res0: Int = 1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions