我有一个类,它带有一个隐式参数,由类方法内部调用的函数使用。我希望能够覆盖该隐式参数并使类及其继承的父类都具有对同一个新隐式对象的引用。
使 Parent 隐含一个 var 并将其设置为新值成功地覆盖了父项中的隐式,但不是子项。
(这类似于 scala: override implicit parameter to constructor ,除了增加了覆盖影响子类和父类的限制。)
例如:
def outside(implicit x: Boolean) {
println(x)
}
class Parent(implicit var x: Boolean) {
def setImplicit() {
x = true
}
def callOutside {
outside
}
}
class Child(implicit x: Boolean) extends Parent {
override def callOutside {
outside
}
}
进而:
scala> val a = new Parent()(false)
a: Parent = Parent@c351f6d
scala> a.callOutside
false
scala> a.setImplicit()
scala> a.callOutside
true // <-- sees the new implicit correctly
scala> val b = new Child()(false)
b: Child = Child@68331dd0
scala> b.callOutside
false
scala> b.setImplicit()
scala> b.callOutside
false // <-- wrong, desire "true" instead
有没有办法获得所需的行为?做诸如使 Parent 和 Child 都隐式成为 var 之类的事情似乎不起作用。谢谢!
最佳答案
你可以
class Parent(x0: Boolean) {
implicit var x = x0
...
}
如果您真的不需要隐式类参数。我会假设你这样做。
一种替代方法是将隐式放在伴随对象上。像这样:
class Parent(x0: Boolean) {
implicit var x = x0
def setImplicit { x = true }
def outsideCall { outside }
}
object Parent {
def apply(implicit x: Boolean) = new Parent(x)
}
class Child(x0: Boolean) extends Parent(x0) {
def callOutside { outside }
}
object Child {
def apply(implicit x: Boolean) = new Child(x)
}
或者,您可以为 Child 创建一个私有(private)的主构造函数(以某种方式装饰,因此它与隐式并不模棱两可)并在辅助构造函数上使用隐式:
class Child private (b: Boolean, u: Unit) extends Parent()(b) {
def this()(implicit x: Boolean) = this(x,())
def callOutside { outside }
}
关于scala:在父类和子类中覆盖构造函数中的隐式var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6826393/