Search code examples
kotlindata-class

How to make attributes in data class non null in kotlin


I have a data class in Kotlin - where there are 5-6 fields,

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

i can initialise the class with DataClass(attribute1="ok", attribute2=null, attribute3= null)

Is there any way to prevent null values in data class ?


Solution

  • Kotlin's type system uses ? to declare nullability. Your data class has fields which are nullable. You can prevent them from being null by removing the ? from their types:

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