Kotlin data class optional variable

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

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

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.

Tags:

Kotlin