scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
232 stars 21 forks source link

-Xlint:implicit-recursion doesn't notice implicit class conversion #12226

Open som-snytt opened 3 years ago

som-snytt commented 3 years ago

reproduction steps

using Scala? Yes.

➜  ✗ scala -nobootcp -Xlint
Welcome to Scala 2.13.3 (OpenJDK 64-Bit Server VM, Java 11.0.7).
Type in expressions for evaluation. Or try :help.

scala> implicit class Elvis[A](alt: => A) { def ?:(a: A): A = if (a ne null) a else alt }
class Elvis

scala> (null: String) ?: "hi"
val res0: String = null

scala> implicit class Elvis[A](alt: => A) { def ?:(a: A): A = if (a ne null) a else alt } // print
implicit class Elvis[A](alt: => A) {
  def ?:(a: A): A = if (Elvis[A](a).ne(null))
    a
  else
    Elvis.this.alt
} // : <notype>
scala> implicit def f[A](a: A): AnyRef = if (a ne null) a else ???
                                                        ^
       error: the result type of an implicit conversion must be more specific than AnyRef
                                             ^
       warning: Implicit resolves to enclosing method f

scala> implicit def f[A](a: A): String = if (a ne null) a else "nope"
                                             ^
       warning: Implicit resolves to enclosing method f

problem

The linter should notice the use of an enclosing implicit thing, as it does for an enclosing method.

Even better, don't go looking to add ne and other AnyRef members to my type. One could argue that it's just a form of boxing, but I don't argue that.

SethTisue commented 3 years ago

Even better, don't go looking to add ne and other AnyRef members to my type

This is a design question not strictly in the scope of this ticket, but perhaps we could work out some rule where we reject AnyRef not only when it is the target type of the conversion, but also when it is the type where the method being searched for is defined. I don't recall if that has ever been proposed before. If that question interests somebody, we should probably discuss it elsewhere.