简体   繁体   中英

scala: how to update super class attributes

I am new to scala and have problem to update attributes.

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.

What is the reason for this behavior?

With val you create immutable fields/variables. Declaring another one in the subclass. If you want to update it use var, in the superclass and assignment in the subclass. 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 = ??? 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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