8

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?

MPelletier
  • 16,256
  • 15
  • 86
  • 137

2 Answers2

30

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

class Person(var firstName: String? = null, var lastName: String? = null)
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Wow. That's elegant. Thanks! – MPelletier Jun 12 '17 at 15:20
  • 1
    *"NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors."* https://kotlinlang.org/docs/reference/classes.html – Arto Bendiken May 17 '18 at 17:35
  • 1
    not able to call Person() with no parameters.. shows compilation error – Siddarth G Jan 17 '20 at 10:07
4

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) {
    }
}
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78