Search code examples
constructorkotlinpojo

Defining a default constructor and a secondary constructor in Kotlin, with properties


I'm trying to make a simple POJO (POKO?) class in Kotlin, with a default empty constructor and a secondary constructor with parameters, that feeds properties

This doesn't give me firstName and lastName properties:

class Person() {

    constructor(firstName: String?, lastName: String?) : this()
}

This gives me the properties, but they're not set after instantiation:

class Person() {

    constructor(firstName: String?, lastName: String?) : this()

    var firstName: String? = null
    var lastName: String? = null
}

And this gives me a compile error saying "'var' on secondary constructor parameter is not allowed.":

class Person() {

    constructor(var firstName: String?, var lastName: String?) : this()
}

So, how is this done? How can I have a default constructor and a secondary constructor with parameters and properties?


Solution

  • You can have just a primary constructor with parameters that have default values:

    class Person(var firstName: String? = null, var lastName: String? = null)