I.D*_*D.M 0 types functional-programming scala function implicit
最近,我对隐式函数产生了兴趣。在文档中,我们可以看到几个使用此属性的示例,但我想我不太明白它是如何工作的。
例如,我们可以读到implicit T0 => R
实际上是
trait ImplicitFunction1[-T0, R] extends Function1[T0, R] {
override def apply(implicit x: T0): R
}
Run Code Online (Sandbox Code Playgroud)
写完下面的函数后
val func = {implicit x: Int => 2*x}
Run Code Online (Sandbox Code Playgroud)
我试图以这种方式使用它
implicit val x: Int = 3
println(func)
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用(只<function1>
返回类型,看起来apply
根本没有使用过)。如果我有一个方法,它会工作得很好
def func(implicit x: Int) = 2*x
Run Code Online (Sandbox Code Playgroud)
我不确定我在这里错过了什么。
隐式函数类型在 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; ???}
。
在 Dotty的所有新implicit
(又名given
)功能中,只有按名称隐式被移植到 Scala 2.13.0。
归档时间: |
|
查看次数: |
381 次 |
最近记录: |