scala:覆盖按名称调用代码块的隐式参数

前端之家收集整理的这篇文章主要介绍了scala:覆盖按名称调用代码块的隐式参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法覆盖控件结构块中调用函数使用的隐式参数?我有一些看起来像这样的代码

def g()(implicit y: Int) {
  // do stuff with y
}

class A {
  implicit val x: Int = 3

  def f() {
    overrideImplicit(...) { // <-- overrideImplicit() is permitted to do anything it wants make it so that g() sees a different implicit val,as long as we do not explicitly declare "implicit" here (though it could happen within the method/function)
      g() // somehow sees the new implicit as opposed to x
    }
  }
}

我的理解是,即使overrideImplicit()设置隐含的内部本身,g()仍然会看到当时在范围内的那个,这是在A中声明的那个.我意识到一种获得所需的方法行为是在f()中明确声明“隐式val x2:Int = 4”,但我想避免这种情况并隐藏使用含义的事实.有没有办法做到这一点?谢谢.

解决方法

这目前正在STM中完成,如下所示:

implicit object globalCtx extends Ctx
val r = ref(0)

atomic { implicit txn =>
  r := 5 // resolves `txn` as the implicit parameter instead of globalCtx
}

所以据我所知,没有比这更好的方法了.至少还没有 – 在SAM(单一抽象方法)类型上看到this discussion并可能将它们添加到Scala.有人建议SAM闭包可以解决这个问题,如果它们被实现,以便在目标类型的上下文中再次解析SAM闭包内的implicits.

@H_502_32@

猜你在找的Scala相关文章