简体   繁体   English

Scala:如何更新超类属性

[英]scala: how to update super class attributes

I am new to scala and have problem to update attributes. 我是scala的新手,无法更新属性。

I have a class that inherits from an abstract class as follows: 我有一个从抽象类继承的类,如下所示:

abstract class A(x:type1,y:type1){
     val z:Option[type1]= None
     def void:type2 
} 

class B extends A(x,y){ 
     def this(x:type1,y:type1,z_:type1)= {this(x,y) val z=Some(z_)}
     def void:type2 = ??? 
}

If I call new B(test,test,test) it doesn't update the value of z which remains None all the time. 如果我调用new B(test,test,test)它不会更新z的值,而z始终保持None

What is the reason for this behavior? 这种行为的原因是什么?

With val you create immutable fields/variables. 使用val可以创建不可变的字段/变量。 Declaring another one in the subclass. 在子类中声明另一个。 If you want to update it use var, in the superclass and assignment in the subclass. 如果要更新它,请在父类中使用var,并在子类中使用赋值。 This should work: 这应该工作:

abstract class A(x:type1,y:type1){
     var z:Option[type1]= None
     def void:type2 
} 

class B extends A(x,y){ 
     def this(x:type1,y:type1,z_:type1)= {this(x,y) z=Some(z_)}
     def void:type2 = ??? 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM