Reputation: 16709
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
Reputation: 29189
There are 2 ways to do this. Both require val
and var
in primary.
class Person(var firstName: String? = null, var lastName: String? = null)
class Person(var firstName: String?, var lastName: String?) {
constructor() : this(null, null) {
}
}
Upvotes: 5
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