Lau*_*ius 2 scala implicit dotty higher-order-functions
我想在包装函数中定义隐式值,并将其提供给内部函数使用,到目前为止,我设法通过从包装器传递隐式变量来做到这一点:
case class B()
trait Helper {
def withImplicit[A]()(block: => A): A = {
implicit val b: B = B()
block
}
}
class Test extends Helper {
def useImplicit()(implicit b: B): Unit = {...}
def test = {
withImplicit() { implicit b: B =>
useImplicit()
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能避免implicit b: B =>,并implicit val b: B = B()提供给内部功能块?
在具有隐式函数类型的Scala 3中,这是可能的(用关键字given代替implicit)
case class B()
trait Helper {
def withImplicit[A]()(block: (given B) => A): A = {
given B = B()
block
}
}
class Test extends Helper {
def useImplicit()(given b: B): Unit = {}
def test = {
withImplicit() {
useImplicit()
}
}
}
Run Code Online (Sandbox Code Playgroud)
https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html
https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |