问题描述
我很难理解如何使以下代码结构起作用。
I am having a hard time understanding how to get the following code structure to work.
在Scala中,我有一个类 MyClass
,它继承自 SomeClass
我在这种情况下添加了一个 var
成员变量,名为 mutableArray
,它正在被重写的方法<$中进行更新c $ c> overridingSomeClassMethod 并在我立即多次创建 MyClass
的新实例时调用。但是当我尝试获取更新的 mutableArray
变量时,在 main
中打印出实例化的 var
好像它是不可变的或只有覆盖方法中的范围。
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.
我无法更改父 SomeClass ,我尝试创建一个伴随对象,并将变量放在包含 SomeOtherObject
中,但我得到了同样的问题。
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
}
}
推荐答案
您可以使用:
case MyClass(...) extends {
var mutableArray: ArrayBuffer[Int] = ArrayBuffer.fill(5)(0)
} with SomeClass(..) {
这篇关于Scala,使用mutable var的类,在重写方法中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!