簡體   English   中英

如何將隱式參數轉化為匿名 function

[英]How to get Implicit parameter into an anonymous function

如何將隱式 val myConnection 放入 execute(true) function 的 scope

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
}

你不能直接這樣做。 調用execute之前真的沒有確定myConnection的值嗎? 在這種情況下,您可以這樣做:

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() 
}

基本上,您將一個參數傳遞給已評估的 function,但您必須記住在調用站點將其標記為隱式。

如果你有幾個這樣的隱式,你可能想把它們放在一個專用的“隱式提供者”class 中。例如:

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中的每個字段提供“隱式 getters” 並編寫如下內容,然后:

implicit def getMyConnection(implicit impl: PassedImplicits) = impl.myConnection

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM