如何在kotlin中使数据class中的属性非空

How to make attributes in data class non null in kotlin

我在 Kotlin 中有一个数据 class - 其中有 5-6 个字段,

data class DataClass(
    val attribute1: String?,
    val attribute2: String?,
    val attribute3: Boolean?
)

我可以用DataClass(attribute1="ok", attribute2=null, attribute3= null)

初始化class

有什么方法可以防止数据中出现空值 class 吗?

Kotlin's type system uses ? to declare nullability。您的数据 class 包含可为空的字段。您可以通过从它们的类型中删除 ? 来防止它们成为 null

data class DataClass(
    val attribute1: String, // not `String?`
    val attribute2: String, // not `String?`
    val attribute3: Boolean // not `Boolean?`
)

fun main() {
    // This line will compile
    val tmp = DataClass(attribute1 = "", attribute2 = "", attribute3 = false)

    // This line will not compile
    val fail = DataClass(attribute1 = null, attribute2 = null, attribute3 = null)
}