方法参数可以作为隐式转换的隐式参数吗?

时间:2011-09-04 03:44:54

标签: scala implicit

REPL会话中的以下代码:

case class Foo(x : Int)

case class Bar(x : Int)

case class Converter(y : Int) {
    def convert(x : Int) = x + y
}

implicit def fooFromBar(b : Bar)(implicit c : Converter) = Foo(c convert (b x))

def roundaboutFoo(x : Int, converter : Converter) : Foo = Bar(x)

给我这个错误:

  

错误:找不到参数c的隐含值:转换器          def roundaboutFoo(x:Int,converter:Converter):Foo =   巴(x)的

如果不明显(暗示),我正在尝试将Bar(x)隐式转换为Foo。隐式转换本身虽然由隐式Converter参数化。我想要使​​用此转换的时间都有一个Converter实例作为方法的参数。

由于Bar不是来自Foo的简单函数,因此无法找到从fooFromBarFoo的隐式转换,因此我预计会因此而死亡到Bar,但我读in this question隐式转换可以有隐式参数,实际上编译器似乎已经计算出这部分。

我找到了another question,详细解答了Scala寻找填充内容的地方。但它只证实了我之前的理解:Scala首先在直接范围内,然后是一堆其他与此无关的地方。

我想知道发生了什么事情是Scala在检查作为隐式参数传递的值的本地范围时不查看本地方法参数。但是向val c = converter添加roundaboutFoo之类的内容并不会更改我收到的错误消息。

这可以使用吗?如果没有,任何人都可以帮助我理解要查找的内容,以确认这样的代码不起作用吗?

1 个答案:

答案 0 :(得分:6)

converter需要是一个隐含参数本身:

def roundaboutFoo(x: Int)(implicit converter: Converter): Foo = Bar(x)

或分配给隐含的val:

def roundaboutFoo(x: Int, converter: Converter): Foo = {
  implicit val conv = converter
  Bar(x)
}

常规参数不是隐式的,因此在尝试填充隐式参数时不会被搜索。

相关问题