你不能直接这样做。myConnection
你打电话之前真的没有确定的价值execute
吗?在这种情况下,您可以这样做:
def execute[T](active: Boolean)(blockOfCode: String => T): Either[Exception, T] = {
val myConnection = "how to get this implicit val into scope"
Right(blockOfCode(myConnection))
}
execute(true) { implicit connection =>
useMyConnection()
}
基本上,您将参数传递给评估函数,但是您必须记住在调用站点将其标记为隐式。
如果你有几个这样的隐式,你可能想把它们放在一个专用的“隐式提供者”类中。例如:
class PassedImplicits(implicit val myConnection: String)
def execute[T](active: Boolean)(blockOfCode: PassedImplicits => T): Either[Exception, T] = {
val myConnection = "how to get this implicit val into scope"
Right(blockOfCode(new PassedImplicits()(myConnection)))
}
execute(true) { impl =>
import impl._
useMyConnection()
}
如果你想避免import
,你可以为你的每个字段提供“隐式getter”PassedImplicits
并编写如下内容,然后:
implicit def getMyConnection(implicit impl: PassedImplicits) = impl.myConnection
execute(true) { implicit impl =>
useMyConnection()
}