why are variables initialized in data class Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of why are variables initialized in data class without wasting too much if your time.

The question is published on by Tutorial Guruji team.

According to the official doc, this is the way to declare a data class

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

but most cases i see where data class is declared thus,

data class User(var username: String? = "", var email: String? = "", var age: Int = 0)

explanation from the docs: On the JVM, if the generated class needs to have a parameterless constructor, default values for all properties have to be specified

i don’t understand, and what are the implications of the different methods

2ndly, what is the best way of writing a data class containing complex object variables such as, ArrayList, Bitmap, Uri


A parameterless constructor would probably only be necessary if you were using the class with some library that generates instances of your class through reflection, such as a serialization library or dependency injection library.

If you put = and some value after a constructor parameter, it allows you to omit that parameter when calling the constructor. The value you put there will be the default value used when the parameter is omitted. This is usually used as a convenience. But if you are using one of the aforementioned libraries, you would also need an empty constructor. By providing defaults for every parameter and annotating the primary constructor with @JvmOverloads, you can satisfy this requirement. It would look like this:

data class User @JvmOverloads constructor(var username: String? = "", var email: String? = "", var age: Int = 0)

If your data class has a lot of properties, you may not want to use @JvmOverloads because the number of constructors it generates is exponentially proportional to the number of properties with defaults. Instead, you can define a secondary constructor like this:

data class User(var username: String?, var email: String?, var age: Int) {
    constructor(): this("", "", 0)

Your second question is very open-ended and opinion-based, so near-impossible to answer in a helpful way.

We are here to answer your question about why are variables initialized in data class - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji