
1. Overview
In this article, we will learn to create an empty constructor for the data class in Kotlin Android.
The primary purpose of this data class is to hold data and doesn’t provide any other functionality. Kotlin generates necessary utility functions for this class including componentN.
The compiler generates the utility methods based on the declaration of the primary constructor. For the data class to work as expected, your primary constructor of the data classes must have:
- at least one parameter.
- parameters should be
val
orvar
.
See the data class article which provides a more detailed description of the data class.
Since we can’t have an empty primary constructor, let’s see other alternatives to create one.
2. Empty or parameterless constructor for data class Kotlin Android
2.1. Assign default values to the primary constructor
You can assign default values to the primary constructor, then an empty constructor is generated automatically by Kotlin.
data class User(var userId: Long = -1, var name: String? = null, val email: String? = null)
You can create a user
instance simply as below:
val user = User()
2.2. Create an empty secondary constructor.
You can declare an empty secondary constructor along with the primary constructor with parameters. Then invoke the primary constructor with default values using the this
keyword from the secondary constructor.
data class User(var userId: Long, var name: String?, val email: String?){ constructor() : this(-1, null, null) }
2.3. No args compiler plugin
You can use the @NoArgs annotation from the no-args compiler plugin to create an empty constructor for the data class.
The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation. The generated constructor is synthetic so it can’t be directly called from Java or Kotlin, but it can be called using reflection.
First, add the dependency
buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version" } } apply plugin: "kotlin-noarg"
plugins { id "org.jetbrains.kotlin.plugin.noarg" version "1.6.10" }
Define an annotation class NoArg
in your project
@Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.SOURCE) annotation class NoArg
Apply the compiler plugin and configure your NoArg
annotation class:
apply plugin: "kotlin-noarg" noArg { annotation("your.path.to.annotaion.NoArg") invokeInitializers = true }
Finally, you can annotate your class using the @NoArg
annotation.
@NoArg data class User(var userId: Long, var name: String?, val email: String?){ }
3. Conclusion
To sum up, we have seen the various solutions to create an empty constructor for data class in Kotlin Android.