我想在包装函数中定义隐式值并使其可用于内部函数,到目前为止我设法通过从包装器传递隐式变量来做到这一点:
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()
}
}
}
是否可以避免 implicit b: B =>
并使 implicit val b: B = B()
可用于内部功能 block ?
最佳答案
这在具有隐式函数类型的 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()
}
}
}
https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html
https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html
关于scala - 如何使隐式可用于内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381138/