Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala:在父类和子类中重写构造函数中的隐式var?_Scala - Fatal编程技术网

scala:在父类和子类中重写构造函数中的隐式var?

scala:在父类和子类中重写构造函数中的隐式var?,scala,Scala,我有一个类,它接受一个隐式参数,该参数由类内方法调用的函数使用。我希望能够覆盖该隐式参数,并使该类及其继承的父类都具有对同一新隐式对象的引用 将父项隐式设置为var并将其设置为新值将成功覆盖父项中的隐式变量,但不会覆盖子项中的隐式变量 (这与类似,只是增加了覆盖同时影响子类和父类的限制。) 例如: def outside(implicit x: Boolean) { println(x) } class Parent(implicit var x: Boolean) { def set

我有一个类,它接受一个隐式参数,该参数由类内方法调用的函数使用。我希望能够覆盖该隐式参数,并使该类及其继承的父类都具有对同一新隐式对象的引用

将父项隐式设置为var并将其设置为新值将成功覆盖父项中的隐式变量,但不会覆盖子项中的隐式变量

(这与类似,只是增加了覆盖同时影响子类和父类的限制。)

例如:

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
scala>val a=new Parent()(false)
a:家长=Parent@c351f6d
scala>a.side
假的
scala>a.setImplicit()
scala>a.side
true//val b=new Child()(false)
b:孩子=Child@68331dd0
scala>b.side
假的
scala>b.setImplicit()
scala>b.side
false/您可以

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)
}
或者,您可以为子构造函数创建一个私有主构造函数(以某种方式进行修饰,这样它就不会与隐式不明确),并在二级构造函数上使用隐式构造函数:

class Child private (b: Boolean, u: Unit) extends Parent()(b) {
  def this()(implicit x: Boolean) = this(x,())
  def callOutside { outside }
}