【问题标题】:Can a method argument serve as an implicit parameter to an implicit conversion?方法参数可以用作隐式转换的隐式参数吗?
【发布时间】:2011-11-09 23:16:32
【问题描述】:

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,转换器:转换器):Foo = 酒吧(x)

如果它不明显(隐式),我想做的是将Bar(x) 隐式转换为Foo。虽然隐式转换本身是由隐式Converter 参数化的。我想使用这种转换的时候都有一个Converter 的实例可用作方法的参数。

由于fooFromBar 不是从FooBar 的简单函数,因此无法找到从BarFoo 的隐式转换,我有一半的预期是这样,但我读到了in this question 隐式转换可以有隐式参数,实际上编译器似乎已经弄清楚了那部分。

我找到了another question,其中提供了详细的答案,特别是关于 Scala 在何处寻找要填充的内容。但这只是证实了我之前的理解:Scala 首先是在直接作用域中查找,然后是一堆其他与这里无关的地方。

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

这可以工作吗?如果没有,谁能帮我理解要寻找什么来识别这样的代码不起作用?

【问题讨论】:

    标签: scala implicit


    【解决方案1】:

    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)
    }
    

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

    【讨论】:

    • 好的,谢谢。我发帖后很快就明白了。不知道为什么我以前从来没有想过。我不知何故错过了您想要 可以隐式传递的隐式值的参数都需要标记为隐式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多