如何将隐式val myConnection放入execute(true)函数的范围
def execute[T](active: Boolean)(blockOfCode: => T): Either[Exception, T] = {
implicit val myConnection = "how to get this implicit val into scope"
Right(blockOfCode)
}
execute(true){
// myConnection is not in scope
useMyConnection() // <- needs implicit value
}
答案 0 :(得分:5)
你不能直接这样做。在致电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()
}
基本上,您将参数传递给已评估的函数,但是您必须记住在调用站点将其标记为隐式。
如果您有几个这样的含义,您可能希望将它们放在专用的“隐式提供者”类中。 E.g:
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
,可以为PassedImplicits
中的每个字段提供“隐式getter”并写下这样的内容,然后:
implicit def getMyConnection(implicit impl: PassedImplicits) = impl.myConnection
execute(true) { implicit impl =>
useMyConnection()
}