Skip to content

Commit

Permalink
Test case for SI-10206
Browse files Browse the repository at this point in the history
Implicit search implements a restriction that the target type for an
implicit view should be more specific that AnyRef or AnyVal.

  scala> def foo(s: String): AnyVal = s
  <console>:12: error: the result type of an implicit conversion must be more specific than AnyVal
         def foo(s: String): AnyVal = s
                                      ^
Without this, an implicit value classes over `String` would be applied,
which is unlikely to be what was intended.

Implicit views are implemented as an implicit search for a function type
with a structural type as its result. This structural type is created
with:

    scala> val schema = analyzer.HasMethodMatching.apply(TermName("clone"), Nil, WildcardType)
    schema: $r.intp.global.analyzer.global.Type = ?{def clone(): ?}

The quirk arises when, as above, we're seeking a member with the same name
as a member of AnyRef. AnyRef is seen to be a subtype of the result type:

   scala> AnyRefClass.tpe <:< schema
   res23: Boolean = true

Which leads to the implicit in the test case being disqualified. The typer
opts to report the error about the inapplicability of the inherited clone
method, so we don't even know why the implicit was discarded.
  • Loading branch information
retronym authored and adriaanm committed Mar 2, 2017
1 parent 78d9173 commit 849d09b
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions test/files/pos/t10206.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Foo(val bar: String)

object Foo {
implicit class Enrich(foo: Foo) {
def clone(x: Int, y: Int): Int = x + y
}
}

object Main extends App {
val foo = new Foo("hello")
println(foo.clone(1, 2)) // <- does not compile
// the implicit view was being disqualified because a new check in the compiler
// that implicit views must not target Any or AnyRef considered an implicit search
// for `foo.type => ?{def clone: ?}` to targeted AnyRef.
}

0 comments on commit 849d09b

Please sign in to comment.