Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class optional variable

Tags:

kotlin

data class Student(     val id: Int?,     val firstName: String?,     val lastName: String?,     val hobbyId: Int?,     val address1: String?,     val address2: String?,     val created: String?,     val updated: String?,     ... ) 

I have like above data class, and I want to create a Student instance with only first name and last name. So If I run this,

// creating a student  Student(     firstName = "Mark"     lastName = "S" ) 

I will get No value passed for parameter 'id' ... errors.

To avoid that, I modified the Student class like this,

data class Student(     val id: Int? = null,     val firstName: String? = null,     val lastName: String? = null,     val hobbyId: Int? = null,     val address1: String? = null,     val address2: String? = null,     val created: String? = null,     val updated: String? = null,     ... ) 

But it looks so ugly.

Is there any better way?

like image 388
Expert wanna be Avatar asked Nov 06 '17 09:11

Expert wanna be


People also ask

How do I make my Kotlin value optional?

The of() method creates an Optional if a value is present, or forces an immediate NullPointerException otherwise. In Kotlin, we have to go out of our way to throw the exception.

Can Kotlin data class have methods?

Data classes specialize in holding data. The Kotlin compiler automatically generates the following functionality for them: A correct, complete, and readable toString() method. Value equality-based equals() and hashCode() methods.

When should I use Kotlin data class?

Answer: Kotlin provides a special type of class called data class, which is usually used for objects that act as a store for data properties and has no business logic or member functions. It provides a lot of advantages with reduced boilerplate code.


1 Answers

You can set default values in your primary constructor as shown below.

data class Student(val id: Int = Int.MIN_VALUE,                val firstName: String,                val lastName: String,                val hobbyId: Int = Int.MIN_VALUE,                val address1: String = "",                val address2: String = "",                val created: String = "",                val updated: String = "") 

Then you can use named arguments when creating a new student instance as shown below.

Student(firstName = "Mark", lastName = "S") 
like image 93
Newbie Avatar answered Sep 23 '22 05:09

Newbie