方法参数可以用作隐式转换的隐式参数吗?
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
不是一个简单的函数,我有一半的预期会因为无法找到从 Bar
到 Foo
的隐式转换而死掉。从 Foo
到 Bar
,但我读了 在这个问题隐式转换可以有隐式参数,事实上编译器似乎已经解决了这部分问题。
我发现另一个问题,其中有一个详细的答案,特别是关于Scala在哪里寻找东西填写隐式。但这只是证实了我之前的理解:Scala 首先查看直接范围,然后查看其他一些与这里不相关的地方。
我想知道发生的情况是否是 Scala 在检查作为隐式参数传递的值的本地范围时不查看本地方法参数。但是向 roundaboutFoo
添加类似 val c = converter
的内容并不会改变我收到的错误消息。
这可以发挥作用吗?如果没有,任何人都可以帮助我了解要寻找什么来识别这样的代码不起作用吗?
The following code in a REPL session:
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)
Gives me this error:
error: could not find implicit value for parameter c: Converter
def roundaboutFoo(x : Int, converter : Converter) : Foo =
Bar(x)
In case it's not obvious (implicits), what I'm trying to do is have Bar(x)
implicitly converted to a Foo
. The implicit conversion itself though is parameterised by an implicit Converter
. The times when I want to use this conversion all have an instance of Converter
available as a parameter to the method.
I half-expected this to die by not being able to find an implicit conversion from Bar
to Foo
, due to fooFromBar
not being a simple function from Foo
to Bar
, but I read in this question that implicit conversions can have implicit parameters, and indeed the compiler seems to have figured that part out.
I found another question with a detailed answer specifically about where Scala looks for things to fill in implicits. But it only confirms my earlier understanding: that Scala looks first in the immediate scope, and then a bunch of other places that aren't relevant here.
I wondered if what was going on was that Scala doesn't look at local method arguments when examining the local scope for values to pass as implicit parameters. But adding something like val c = converter
to roundaboutFoo
doesn't change the error message I get.
Can this be made to work? If not, can anyone help me understand what to look for to recognise that code like this isn't going to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
converter
本身需要是隐式参数:或者分配给隐式 val:
常规参数不是隐式的,因此在尝试填充隐式参数时不会被搜索。
converter
needs to either be an implicit parameter itself:or assigned to an implicit val:
Regular parameters are not implicit, and thus aren't searched when trying to fill in an implicit argument.