Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Kotlin data class have more than one constructor?

I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age: Int) 

Is it possible to declare a second constructor for that data class?

like image 440
Eder Padilla Avatar asked Jun 06 '17 13:06

Eder Padilla


People also ask

How many constructors can a Kotlin class have?

Constructors A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is a part of the class header, and it goes after the class name and optional type parameters.

Can we have secondary constructor in Kotlin?

In Kotlin, a class can also contain one or more secondary constructors. They are created using constructor keyword. Secondary constructors are not that common in Kotlin.


1 Answers

A Kotlin data class must have a primary constructor that defines at least one member. Other than that, you can add secondary constructors as explained in Classes and Inheritance - Secondary Constructors.

For your class, and example secondary constructor:

data class User(val name: String, val age: Int) {     constructor(name: String): this(name, -1) { ... } } 

Notice that the secondary constructor must delegate to the primary constructor in its definition.

Although many things common to secondary constructors can be solved by having default values for the parameters. In the case above, you could simplify to:

data class User(val name: String, val age: Int = -1)  

If calling these from Java, you should read the Java interop - Java calling Kotlin documentation on how to generate overloads, and maybe sometimes the NoArg Compiler Plugin for other special cases.

like image 178
Jayson Minard Avatar answered Oct 13 '22 05:10

Jayson Minard