kotlin

Kotlin data class optional variable


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?


Solution

  • 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, "", "", "", "")
    }