gpt4 book ai didi

scala:将隐式参数覆盖到构造函数

转载 作者:行者123 更新时间:2023-12-04 17:12:45 25 4
gpt4 key购买 nike

我有一个类,它接受一个隐式参数,该参数由在类方法中调用的函数使用。我希望能够覆盖该隐式参数,或者从其源复制隐式参数。举个例子:

def someMethod()(implicit p: List[Int]) {
// uses p
}

class A()(implicit x: List[Int]) {

implicit val other = List(3) // doesn't compile

def go() { // don't want to put implicit inside here since subclasses that override go() have to duplicate that
someMethod()
}
}

我想要的行为是 someMethod() 获取一个隐式参数,它是 x 的某个更改版本,它是类的隐式参数。我希望能够改变 x 而不改变它传递给 A 的构造函数的任何内容,或者以其他方式将其覆盖为我选择的新值。这两种方法似乎都不起作用。也就是说,在前一种情况下它不会复制列表,而编译器会为后一种情况找到一个不明确的隐式值。有没有办法做到这一点?

我意识到我可以在 go() 中重新定义隐式值,但在我的情况下这不是一个好的选择,因为这个类被多次子类化,我只想在基类中处理这种隐式更改。所以它不一定需要在构造函数中,但它必须在 go() 以外的方法中。

最佳答案

引入另一种包装器类型,只是为了消除歧义:

//  badly named, choose something domain-specific
case class ListHolder(theList: List[Int])

def someMethod()(implicit holder: ListHolder) {
val xs = holder.theList
// uses xs ...
}

class A()(implicit xs: List[Int]) {

implicit val other = ListHolder(42 :: xs) // compiles

def go() {
// xs is never considered for the implicit param to someMethod()
// because it's now the wrong type
}
}

这也使代码更具自文档性,因为这两个隐式不是一回事变得非常明显。

关于scala:将隐式参数覆盖到构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5962122/

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