Scala 方法参数能否作为隐式转换的隐式参数?

Scala 方法参数能否作为隐式转换的隐式参数?,scala,implicit,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

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环形交叉口Foo(x:Int,converter:converter):Foo= 巴(x)

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

由于
fooFromBar
不是一个从
Foo
Bar
的简单函数,因此无法找到从
Bar
Foo
的隐式转换,我有一半的希望这种情况会消失,但我读到隐式转换可以有隐式参数,事实上,编译器似乎已经解决了这一部分

我找到了一个详细的答案,特别是关于Scala在哪里查找要填充的内容。但这只证实了我之前的理解:Scala首先在直接范围内查看,然后是其他一些与此无关的地方

我想知道是不是Scala在检查作为隐式参数传递的值的局部范围时没有查看局部方法参数。但是向
roundaboutFoo
添加类似于
val c=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)
}

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

转换器
需要是隐式参数本身:

def roundaboutFoo(x: Int)(implicit converter: Converter): Foo = Bar(x)
或分配给隐式val:

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

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

是的,谢谢。我在发帖后很快就明白了。不知道为什么我以前从未想到过。不知何故,我忽略了您想要隐式值的参数和可以隐式传递的值都需要标记为隐式。是的,谢谢。我在发帖后很快就明白了。不知道为什么我以前从未想到过。不知何故,我忽略了您想要隐式值的参数和可以隐式传递的值都需要标记为隐式。