Search code examples
classkotlinsubclasssubclassing

Kotlin – Why parameter values have to be passed in sub classes?


My code:

open class Club(name: String, country: String)

class FemaleClub(): Club()

var femaleClub = FemaleClub("Blue", "Australia")

Why is the above code not possible?

Why does it have the error

no value passed for parameter name

and

no value passed for parameter country

in my subclass? The values are set when I initiate femaleClub.


Solution

  • In your example parent class Club has primary constructor which is, by language specification, must be called either from secondary constructors of the same class or primary constructor of subclasses to initialize parameters defined in primary constructor. If you don't want to call a primary constructor of a parent class from subclasses you have a couple of options:

    1. Set default values to parameters of primary constructor:

      open class Club(name: String = "DefaultName", country: String = "Country") {
      }
      

      In this case you will not be able to call primary constructor with params:

      // this is not possible
      var femaleClub = FemaleClub("Blue", "Australia")
      
    2. Create secondary constructor in parent class which calls primary constructor:

      open class Club(name: String, country: String) {
      
          constructor(): this("Name", "Country")
      }
      

      But also you won't be able to call FemaleClub("Blue", "Australia").

    To be able to call constructor with parameters of a subclass FemaleClub("Blue", "Australia") you need explicitly define them in primary constructor of the subclass and call parent's primary constructor, i.e.:

    class FemaleClub(name: String, country: String): Club(name, country) {}