scala:覆盖按名称调用代码块的隐式参数
发布时间:2020-12-16 18:02:40 所属栏目:安全 来源:网络整理
导读:有没有办法覆盖控件结构块中调用的函数使用的隐式参数?我有一些看起来像这样的代码: def g()(implicit y: Int) { // do stuff with y}class A { implicit val x: Int = 3 def f() { overrideImplicit(...) { // -- overrideImplicit() is permitted to do
有没有办法覆盖控件结构块中调用的函数使用的隐式参数?我有一些看起来像这样的代码:
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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |