关于Scala隐式转换非二义性规则的问题
有人可以用 Scala 隐式转换机制向我解释以下情况吗?有一个代码:
object Main {
implicit val x:Int => String = v => "val"
implicit def y(v:Int) = "def"
def p(s:String) = print(s)
def main(args: Array[String]): Unit = {
p(1)
}
}
该代码打印“val”。但是当我评论第二行时:
//implicit val x:Int => String = v => "val"
代码打印“def”。
因此,在这种情况下,两种隐式转换(x 和 y)都是可能的。有一个无歧义规则 - 仅当没有其他可能的转换可插入时才会插入隐式转换。根据这条规则,这段代码根本不应该被编译。但代码已成功编译并执行。我不明白什么?
谢谢。
Could anybody explain me following situation with Scala implicit conversions mechanism. There is a code:
object Main {
implicit val x:Int => String = v => "val"
implicit def y(v:Int) = "def"
def p(s:String) = print(s)
def main(args: Array[String]): Unit = {
p(1)
}
}
This code prints "val". But when I comment second line:
//implicit val x:Int => String = v => "val"
code prints "def".
So both implicit conversions (x and y) are possible in this situation. There is a Non-Ambiguity Rule - an implicit conversion is only inserted if there is no other possible conversion to insert. According to this rule this code shouldn't be compiled at all. But the code is successfully compiled and executed. What I don't understand?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scala 语言规范第 6.26.2 节中说明了其原因。
在将该方法视为函数之前,需要通过执行 eta 扩展将其转换为函数。因此,必须再应用一次隐式转换,因此选择
val
。更新:删除了有缺陷的示例。
不带参数的方法的评估总是隐式执行的。
The reason for this is stated in the Scala Language Specification section 6.26.2.
Before the method can be treated as a function it needs to be converted to one by performing eta-expansion. Thus one more implicit conversion would have to be applied and so the
val
is chosen.UPDATE: removed flawed example.
Evaluation of a method without parameters is always performed implicitly.