方法参数可以用作隐式转换的隐式参数吗? [英] Can a method argument serve as an implicit parameter to an implicit conversion?

查看:122
本文介绍了方法参数可以用作隐式转换的隐式参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

REPL会话中的以下代码:

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)

给我这个错误:

错误:找不到参数c的隐式值:转换器 def roundaboutFoo(x:整数,转换器:转换器):Foo = 栏(x)

error: could not find implicit value for parameter c: Converter def roundaboutFoo(x : Int, converter : Converter) : Foo = Bar(x)

如果不太明显(隐含),我想做的就是将Bar(x)隐式转换为Foo.但是,隐式转换本身由隐式Converter参数化.在我想使用此转换的所有时间中,都有一个Converter实例可用作该方法的参数.

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.

由于fooFromBar不是从FooBar的简单函数,所以我一半无法解决从BarFoo的隐式转换,但我读了一半在该问题中隐式转换可以具有隐式参数,并且实际上编译器似乎具有想通了那部分.

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.

我发现了另一个问题,其中包含有关Scala外观的详细答案用于填充隐式的东西.但这只是证实了我以前的理解:Scala首先在最近的范围内看起来,然后在这里其他与之无关的其他地方.

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.

我想知道发生的事情是,Scala在检查局部范围以作为隐式参数传递的值时没有查看局部方法参数.但是,将val c = converter之类的内容添加到roundaboutFoo并不会改变我收到的错误消息.

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?

推荐答案

converter本身必须是一个隐式参数:

converter needs to either be an implicit parameter itself:

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

或分配给隐式val:

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

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

Regular parameters are not implicit, and thus aren't searched when trying to fill in an implicit argument.

这篇关于方法参数可以用作隐式转换的隐式参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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