考虑以下代码:
class A { def print = println("A") }
class B extends A { override def print = println("B") }
def foo(implicit a: A) = a.print
def bar(implicit a: A) = {
implicit val b = new B
foo
}
bar(new A) // B
我想知道为什么在
foo
中调用bar
不会引发ambiguous implicit values
错误。当然implicit val b: A = new B
将引发该错误。为什么
foo
选择隐式b
而不选择隐式a
?或更笼统:将遵循哪些规则?编辑:
由于我与Ivan进行了评论对话,因此我想澄清一下:如果我以与隐式方法参数相同的方式命名本地隐式val,那么我就会知道问题的答案。
def bar(implicit a: A) = {
implicit val a = new B
foo
}
然后,只有本地
val a
在作用域内,该作用域将覆盖method参数,因为它们具有相同的名称。
最佳答案
注意:我可能在很大程度上简化了事情,但是在测试中似乎如下所示。
这是因为第二个在内部范围内,所以它具有优先权。这与发生的事情相同
object test {
val a = 5
def test(i: Int) = {
val a = 6
i + a
}
}
在这种情况下,您希望
a
在函数内部为6。以下是类似的。object test {
implicit val i = 5;
{
implicit val b = 6;
test
}
def test(implicit ii:Int) = println(ii)
}
从评论更新。
scala> def test(a: Int) = {val a = 5; a }
test: (a: Int)Int
scala> test(6)
res1: Int = 5
关于scala - 明确的隐含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526345/