简体   繁体   English

如何将隐式参数转化为匿名 function

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

How do I get the implicit val myConnection into scope of the execute(true) 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
}

You can't do this directly.你不能直接这样做。 Is the value of myConnection really not determined before you call execute ?调用execute之前真的没有确定myConnection的值吗? In this case, you could do this:在这种情况下,您可以这样做:

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

Basically, you pass a parameter to the evaluated function, but then you have to remember to mark it implicit at the call site.基本上,您将一个参数传递给已评估的 function,但您必须记住在调用站点将其标记为隐式。

If you have several such implicits, you may want to put them in a dedicated, “implicit provider” class. Eg:如果你有几个这样的隐式,你可能想把它们放在一个专用的“隐式提供者”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() 
}

If you want to avoid the import , you can provide “implicit getters” for each of your fields in PassedImplicits and write something like this, then:如果你想避免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