gpt4 book ai didi

scala - 如何将隐式参数放入匿名函数中

转载 作者:行者123 更新时间:2023-12-05 01:30:01 25 4
gpt4 key购买 nike

如何将隐式 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
}

最佳答案

你不能直接这样做。是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 ,您可以为 PassedImplicits 中的每个字段提供“隐式 setter/getter ”。并写下这样的东西,然后:
implicit def getMyConnection(implicit impl: PassedImplicits) = impl.myConnection

execute(true) { implicit impl =>
useMyConnection()
}

关于scala - 如何将隐式参数放入匿名函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10011643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com