gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:04:08 27 4
gpt4 key购买 nike

有没有办法覆盖控制结构 block 内调用的函数使用的隐式参数?我有一些看起来像这样的代码:

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
}

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

关于scala:覆盖按名称调用代码块周围的隐式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com