我在Kotlin有一个数据类,那里有5-6个字段,
data class DataClass(
val attribute1: String?,
val attribute2: String?,
val attribute3: Boolean?
)我可以用DataClass(attribute1="ok", attribute2=null, attribute3= null)初始化这个类
是否有任何方法来防止数据类中的空值?
发布于 2019-07-24 17:39:52
to declare nullability。您的数据类有可空的字段。您可以通过从它们的类型中删除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)
}https://stackoverflow.com/questions/57183008
复制相似问题