Reputation: 10624
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?
Upvotes: 60
Views: 68491
Reputation: 1200
data class InLog(
var clock_in_lat: String?="None",
var clock_in_lng: String?="None",
var clock_out_lat: String?="None",
val clock_out_lng: String?="None",
val created_at: String?="None",
val duration: String?="None",
val end_time: String?="None",
val id: Int?=Int.MIN_VALUE,
var late_duration: String? = "None",
val start_time: String?="None",
val type: String?="None",
val updated_at: String?="None",
val user_id: Int?=Int.MIN_VALUE)
in Kotlin we do like that remeber ? mark symbol use.
Upvotes: 0
Reputation: 7249
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")
Upvotes: 71
Reputation: 6092
I am not sure the solution I am giving you is the best or not. But definitely neat.
The only thing I don't like to go with nulls as default param, because Kotlin offers Null Safety, lets not remove it just because to fulfil some other requirement. Mark them null only if they can be null. Else old Java way is good. Initialize them with some default value.
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) {
constructor(firstName: String, lastName: String) :
this(Int.MIN_VALUE, firstName, lastName, Int.MIN_VALUE, "", "", "", "")
}
Upvotes: 28