Scala 中的隐式转换和隐式参数之间有什么关系?

What is the relationship between implicit conversions and implicit parameters in Scala?

Scala中隐式转换和隐式参数之间有关系吗?

我对了解什么是不同类型的隐式或者它们的解析规则是什么没有兴趣。

我只对这两个概念为什么重名感兴趣。

从类型 A 到类型 B 的隐式 转换 是隐式 函数 A => B.

隐式 def 使隐式函数可用:

// two types
class A
class B
// implicit conversion from A to B
implicit def aToB(a: A): B = {
  println("aToB");
  new B
}
// we now have a Function[A, B] aka A => B in the implicit scope
val f = implicitly[A => B]
f(new A)
> aToB
res1: B = B@51931956

隐式函数启用隐式转换:

class IntExtension(x: Int) { def isPositive = x > 0 }
implicit val intToIntExtensions: Int => IntExtension = x => new IntExtension(x)
> 1.isPositive
res2: Boolean = true

据我所知,除了共享相同的关键字外,没有任何直接关系。

但它们可以以一种有趣的方式组合,例如:

class Foo
class Bar
class FooBar(foo: Foo, bar: Bar)

implicit val foo = new Foo
implicit val bar = new Bar

implicit def fooBar(implicit foo: Foo, bar: Bar): FooBar = new FooBar(foo, bar)

implicitly[FooBar]

implicit conversion(花哨的名字,但实际上只不过是一个接受参数的隐式)可以接受 implicit parameters 的行为非常像 implicit val(给定的隐式已定义)。轰.