Why does Scala implicit resolution fail for overloaded method with type parameter?

青春壹個敷衍的年華 提交于 2019-11-29 19:29:12

问题


The first example successfully finds the implicit conversion to the method foo(String), however as soon as I add a type parameter (see fails) the compiles doesn't resolve it anymore:

object works {
  class A {
    def foo(): String = ???
  }
  implicit class PimpedA(a: A) {
    def foo(i: String): String = ???
  }
  val a = new A()
  a.foo("test") //compiles
}

object fails { //same as `works`, but adds type parameter
  class A {
    def foo[T](): String = ???
  }
  implicit class PimpedA(a: A) {
    def foo[T](i: String): String = ???
  }
  val a = new A()
  PimpedA(a).foo("test") // compiles
  a.foo("test") // error: too many arguments for method foo: ()String
}

This behaviour is the same for Scala 2.11.7 and 2.12.0-M3.

The documentation on implicits doesn't seem to cover this and I didn't find this exact case on stackoverflow.

Note that my goal is to overload the method foo - if i rename it, the compiler finds it.

http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html


回答1:


Both cases seem to fall under this case of the specification:

Views are applied in three situations:

...

In a selection e.m(args) with e of type T, if the selector m denotes some member(s) of T, but none of these members is applicable to the arguments args. In this case a view v is searched which is applicable to e and whose result contains a method m which is applicable to args. The search proceeds as in the case of implicit parameters, where the implicit scope is the one of T. If such a view is found, the selection e.m is converted to v(e).m(args).

So it should work. I was actually surprised to see it, because I've never run into the working case before and assumed that there is no implicit search if T has any members named m. I've taken a quick look at http://issues.scala-lang.org/, but couldn't find a relevant issue.



来源:https://stackoverflow.com/questions/33162618/why-does-scala-implicit-resolution-fail-for-overloaded-method-with-type-paramete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!