Kotlin数据类可选变量

时间:2017-11-06 09:55:27

标签: kotlin

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?,
    ...
)

我喜欢上面的数据类,我想创建一个只有名字和姓氏的Student实例。 所以如果我运行它,

// creating a student 
Student(
    firstName = "Mark"
    lastName = "S"
)

我会得到参数'id'没有传递值... 错误。

为了避免这种情况,我修改了这样的Student类,

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,
    ...
)

但它看起来很难看。

还有更好的方法吗?

3 个答案:

答案 0 :(得分:17)

您可以设置default values in your primary constructor,如下所示。

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

然后,您可以在创建新学生实例时使用命名参数,如下所示。

Student(firstName = "Mark", lastName = "S")

答案 1 :(得分:10)

我不确定我给你的解决方案是否是最好的。但绝对整洁。

我唯一不喜欢使用null作为默认参数,因为Kotlin提供Null Safety,不要因为满足其他要求而删除它。仅当它们可以为null时才将它们标记为null。其他旧的Java方式很好。用一些默认值初始化它们。

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 :(得分:0)

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) 

在 Kotlin 中,我们确实喜欢这样的记忆?标记符号使用。