Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
MPelletier Avatar asked Jun 12 '17 15:06

MPelletier


People also ask

How does Kotlin define secondary constructor?

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.

How do you create a primary and secondary constructor in Kotlin?

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.

What are the two types of constructors in Kotlin?

A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.


1 Answers

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

class Person(var firstName: String? = null, var lastName: String? = null)
like image 190
zsmb13 Avatar answered Oct 18 '22 06:10

zsmb13