明确的隐含 [英] Unambiguous Subimplicits

查看:64
本文介绍了明确的隐含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

我想知道为什么在bar中调用foo不会引发ambiguous implicit values错误.当然

I am wondering why calling foo in bar isn't raising an ambiguous implicit values error. Of course

implicit val b: A = new B

将引发该错误.为什么foo选择隐式b而不选择隐式a?或更笼统:将遵循哪些规则?

will raise that error. Why does foo pick the implicit b and not the implicit a? Or even more general: What are the rules what will be picked?


由于我与Ivan进行了评论对话,因此我想澄清一下:如果我以与隐式方法参数相同的方式命名本地隐式val,那么我就会知道问题的答案.


Due to my comment-conversation with Ivan I want to clarify: I would know the answer to my question if I named the local implicit val the same way as the implicit method parameter.

def bar(implicit a: A) = {
  implicit val a = new B
  foo
}

然后只有局部val a处于作用域内,该作用域将覆盖方法参数,因为它们具有相同的名称.

Then only the local val a is in scope which scope-overrides the method parameter because they have the same name.

推荐答案

注意:我可能在很大程度上简化了事情,但是在测试中似乎如下.

Note: I'm probably vastly oversimplying things, but in testing it seemed like the following.

因为第二个在内部范围内,所以它具有优先权.

It's because the 2nd one is in an inner scope, so it has precedence. Its the same thing that happens with

object test {
 val a = 5
 def test(i: Int) = {
   val a  = 6
   i + a
 }
}

在这种情况下,您希望函数中的a为6.以下是相似的.

In this case you would expect a to be 6 inside the function. The following is similar.

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

这篇关于明确的隐含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆