加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么Scala隐式解析对于带有类型参数的重载方法失败?

发布时间:2020-12-16 09:27:18 所属栏目:安全 来源:网络整理
导读:第一个示例成功找到了对方法foo(String)的隐式转换,但是只要我添加一个类型参数(请参阅失败),编译就不再解析它: object works { class A { def foo(): String = ??? } implicit class PimpedA(a: A) { def foo(i: String): String = ??? } val a = new A()
第一个示例成功找到了对方法foo(String)的隐式转换,但是只要我添加一个类型参数(请参阅失败),编译就不再解析它:

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的行为相同.

关于implicits的文档似乎没有涵盖这一点,我没有在stackoverflow上找到这个确切的情况.

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

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

解决方法

这两种情况似乎属于 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).

所以它应该工作.我真的很惊讶地看到它,因为我之前从未遇到过工作案例,并且假设如果T有任何名为m的成员,则没有隐式搜索.我快速浏览了http://issues.scala-lang.org/,但未找到相关问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读