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

查看:22
本文介绍了为什么带有类型参数的重载方法的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.

关于implicits 的文档似乎没有涵盖这一点,而且我在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:

视图应用于三种情况:

...

em(args)e 类型 T 的选择中,如果选择器 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天全站免登陆