MPelletier
MPelletier

Reputation: 16709

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?

Upvotes: 10

Views: 29739

Answers (2)

Steven Spungin
Steven Spungin

Reputation: 29189

There are 2 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 Primary

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

Upvotes: 5

zsmb13
zsmb13

Reputation: 89678

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

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

Upvotes: 32

Related Questions