问题
I am having a hard time understanding how to get the following code structure to work.
In Scala I have a class MyClass which inherits from SomeClass I added a var member variable in this case called mutableArray and it is being updated in the overridden method overridingSomeClassMethod and is called when I create a new instance of the MyClass a number of times right away. But in main when I try and get the updated mutableArray variable it prints out the instantiated var as if it is immutable or only has scope in the overriding method.
I can't change the method in parent SomeClass, and I tried creating a companion object as well as putting the variable in the encompassing SomeOtherObject but I get the same exact issue.
import scala.collection.mutable.ArrayBuffer
object SomeOtherObject{
case MyClass(...) extends SomeClass(..){
var mutableArray: ArrayBuffer[Int] = ArrayBuffer.fill(5)(0)
def overridingSomeClassMethod(...){
var someReturnVar = 0.0
mutableArray(0) += 1
println(mutableArray.mkString) // last output -> 84169
someReturnVar
}
}
def main(args: Array[String]){
var mc = new MyClass
println(mc.mutableArray.mkString) // output -> 00000
}
}
回答1:
You can use an early initializer:
case MyClass(...) extends {
var mutableArray: ArrayBuffer[Int] = ArrayBuffer.fill(5)(0)
} with SomeClass(..) {
回答2:
Probably you are hitting the infamous "one question FAQ" about initialization order.
If the method is invoked by the superclass constructor, then your initialization happens after that, resetting the data to zero.
来源:https://stackoverflow.com/questions/33248520/scala-class-using-mutable-var-update-in-overriding-method