加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何将隐式参数导入匿名函数

发布时间:2020-12-16 10:03:16 所属栏目:安全 来源:网络整理
导读:如何将隐式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){// my
如何将隐式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
}

解决方法

你不能直接这样做.在调用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() 
}

基本上,您将参数传递给evaluate函数,但是您必须记住在调用站点上隐式标记它.

如果您有几个这样的含义,您可能希望将它们放在专用的“隐式提供者”类中.例如.:

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

如果你想避免导入,你可以为PassedImplicits中的每个字段提供“隐式getter”并写下这样的东西,然后:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读