Search code examples
kotlinconstructorclass-constructors

more parameters in constructor of subclass in kotlin


I am newbie . I want add age parameter in Employee class drived from Person class. how can I do that in kotlin?!

abstract class Person constructor (var name :String ,var gender :String) {
}

I got error with this way:

class Employee() : Person() {
    constructor(age : Int ) : super (name , gender)
} 

and why can not use var or val in Employee constructor?! What is my mistake?


Solution

  • Use primary constructor for that:

    class Employee(name: String, gender: String, val age: Int) : Person(name, gender) {} 
    

    When you have a primary constructor with some parameters in a parent class, you should specify the same constructor in its subclass plus additional parameters if need.