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?
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With