为什么对于带类型参数的重载方法,Scala隐式解析失败? [英] Why does Scala implicit resolution fail for overloaded method with type parameter?

查看:172
本文介绍了为什么对于带类型参数的重载方法,Scala隐式解析失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个示例成功找到了方法foo(String)的隐式转换,但是,一旦添加类型参数(请参见fails),编译器便不再解析它:

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
}

对于Scala 2.11.7和2.12.0-M3,此行为相同.

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

关于隐式的文档似乎没有涵盖这一点,我在stackoverflow上也找不到这种确切的情况.

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

请注意,我的目标是重载方法foo-如果我重命名方法,则编译器会找到它.

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

推荐答案

这两种情况似乎都属于

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

视图在三种情况下适用:

Views are applied in three situations:

...

在类型为Te的选择e.m(args)中,如果选择器m表示T的某些成员,但这些成员均不适用于参数args.在这种情况下,将搜索适用于e的视图v,其结果包含适用于args的方法m.搜索与隐式参数一样进行,其中隐式范围是T之一.如果找到这样的视图,则选择e.m将转换为v(e).m(args).

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

因此它应该可以工作.看到它确实让我感到惊讶,因为我以前从未遇到过这种工作情况,并假设如果T有任何名为m的成员,则没有隐式搜索.我快速浏览了 http://issues.scala-lang.org/,但找不到相关问题.

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.

这篇关于为什么对于带类型参数的重载方法,Scala隐式解析失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆