Defining default constructor and secondary constructor in Kotlin with properties

I am trying to create a simple POJO (POKO?) Class in Kotlin, with an empty default constructor and an additional parameterized constructor that passes properties

This gives me no properties firstName

and lastName

:

class Person() {

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

      

This gives me properties, but they are not set after instantiation:

class Person() {

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

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

      

And it gives me a compile error: "var" for secondary constructor parameter is not allowed. ":

class Person() {

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

      

So how is it done? How can I create a default constructor and an additional constructor with parameters and properties?

+3


source to share


2 answers


You can only be the primary constructor parameters defaults :



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

      

+11


source


There are two ways to do this. Both require val

and var

in primary.

Default parameters in primary

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

      



Secondary constructor calling the primary

class Person(var firstName: String?, var lastName: String?) {
    constructor() : this(null, null) {
    }
}

      

0


source







All Articles