Kotlin data class optional variable

2020-04-02 07:42发布

问题:

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?

回答1:

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


回答2:

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")


标签: kotlin