Scala 中的隐式函数类型
Implicit function types in Scala
最近对隐式函数产生了兴趣。在documentation中,我们可以看到几个使用这个属性的例子,但我想我不太明白它是如何工作的。
例如,我们可以读出 implicit T0 => R
实际上是
trait ImplicitFunction1[-T0, R] extends Function1[T0, R] {
override def apply(implicit x: T0): R
}
写完下面的函数
val func = {implicit x: Int => 2*x}
我试过这样用
implicit val x: Int = 3
println(func)
但是好像不行(只返回<function1>
类型,好像根本没用过apply
)。如果我有一个方法,它会很好用
def func(implicit x: Int) = 2*x
我不确定我在这里遗漏了什么。
隐式函数类型适用于 Dotty
https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html
https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html
在 Scala 2 中 func
具有类型 Int => Int
而不是不存在 implicit Int => Int
(又名 given Int => Int
)。
implicit x: Int => ???
只是 x: Int => { implicit val _x: Int = x; ???}
的 shorthand。
在 Dotty 中的所有新 implicit
(又名 given
)功能中,只有名称隐式被反向移植到 Scala 2.13.0。
最近对隐式函数产生了兴趣。在documentation中,我们可以看到几个使用这个属性的例子,但我想我不太明白它是如何工作的。
例如,我们可以读出 implicit T0 => R
实际上是
trait ImplicitFunction1[-T0, R] extends Function1[T0, R] {
override def apply(implicit x: T0): R
}
写完下面的函数
val func = {implicit x: Int => 2*x}
我试过这样用
implicit val x: Int = 3
println(func)
但是好像不行(只返回<function1>
类型,好像根本没用过apply
)。如果我有一个方法,它会很好用
def func(implicit x: Int) = 2*x
我不确定我在这里遗漏了什么。
隐式函数类型适用于 Dotty
https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html
https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html
在 Scala 2 中 func
具有类型 Int => Int
而不是不存在 implicit Int => Int
(又名 given Int => Int
)。
implicit x: Int => ???
只是 x: Int => { implicit val _x: Int = x; ???}
的 shorthand。
在 Dotty 中的所有新 implicit
(又名 given
)功能中,只有名称隐式被反向移植到 Scala 2.13.0。