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?
To do so you need to declare a secondary constructor using the constructor keyword. If you want to use some property inside the secondary constructor, then declare the property inside the class and use it in the secondary constructor. By doing so, the declared variable will not be accessed inside the init() block.
The primary constructor is initialized in the class header, goes after the class name, using the constructor keyword. The parameters are optional in the primary constructor. The constructor keyword can be omitted if there is no annotations or access modifiers specified.
A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.
You can have just a primary constructor with parameters that have default values:
class Person(var firstName: String? = null, var lastName: String? = null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With