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

scala – 为什么我们必须显式导入具有来自伴随对象的隐式参数的

发布时间:2020-12-16 18:35:45 所属栏目:安全 来源:网络整理
导读:我们考虑一下这段代码: class Aobject A{ implicit def A2Int(implicit a:A)=1 implicit def A2String(a:A)="Hello"}object Run extends App{ implicit val a: A =new A import A.A2Int // without this import this code does not compile,why ? // why is
我们考虑一下这段代码:

class A
object A{
  implicit def A2Int(implicit a:A)=1
  implicit def A2String(a:A)="Hello"
}

object Run extends App{
  implicit val a: A =new A

  import A.A2Int
  // without this import this code does not compile,why ?
  // why is no import needed for A2String then ?

  def iWantInt(implicit i:Int)=println(i)
  def iWantString(implicit s:String)=println(s)

  iWantInt
  iWantString(a)
}

它运行和打印:

1
Hello

现在,如果我们注释掉这条线

import A.A2Int

然后我们得到一个编译错误:

随着该行的注释,为什么Scala找不到A.A2String,如果能找到A.A2Int?

如何解决这个问题?

谢谢阅读.

解决方法

不同之处在于,当你执行iWantString(a)时,编译器会得到一些起点:你明确地传递一个,编译器知道它是A类型.
假设iWantString采用String而不是A,编译器将搜索从A到String的隐式转换,以便插入它并使调用成功.
隐式查找规则声明编译器必须在类A的伴随对象中查找(以及其他位置),因为类型A是转换的源类型.
这是它找到隐式转换A2String的地方.
你必须得到的是,它只是因为你传递了一个A的实例,编译器知道这个实例寻找隐式转换到A的伴随对象.

当你只是运行iWantInt时,编译器没有理由查看A,因此它不会找到你的方法A2Int(并且由于scope中没有其他方法/值提供Int类型的隐式值,因此编译失败).

有关隐式查找规则的更多信息,请参阅
请参阅http://www.scala-lang.org/docu/files/ScalaReference.pdf(第7.2章)中的scala规范.这是最相关的摘录:

The implicit scope of a type T consists of all companion modules (§5.4) of classes that are associated with the implicit parameter’s type.

(编辑:李大同)

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

    推荐文章
      热点阅读