1

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 ?

2
  • 3
    The point of ? is to allow null values, so just remove it. Commented Jul 24, 2019 at 12:32
  • var attribute2: String = "", var attribute3: Boolean = false, like this? Commented Jul 24, 2019 at 12:33

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.