4.10. Handling Constructor Parameters When Extending a Class
Problem
You want to extend a base class, and need to work with the constructor parameters declared in the base class, as well as new parameters in the subclass.
Solution
Declare your base class as usual with val or var
constructor parameters. When defining a subclass constructor, leave the
val or var declaration off of the fields that are
common to both classes. Then define new constructor parameters in the
subclass as val or var fields, as usual.
For example, first define a Person base class:
classPerson(varname:String,varaddress:Address){overridedeftoString=if(address==null)nameelses"$name @ $address"}
Next define Employee as a
subclass of Person, so that it takes
the constructor parameters name,
address, and age. The name and address parameters are common to the parent
Person class, so leave the var declaration off of those fields, but
age is new, so declare it as a
var:
classEmployee(name:String,address:Address,varage:Int)extendsPerson(name,address){// rest of the class}
With this Employee class and an
Address case class:
caseclassAddress(city:String,state:String)
you can create a new Employee
as follows:
valteresa=newEmployee("Teresa",Address("Louisville","KY"),25)
By placing all that code in the REPL, you can see that all of the fields work as expected:
scala>teresa.nameres0: String = Teresa scala>teresa.addressres1: Address = Address(Louisville,KY) scala>teresa.ageres2: Int ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access