Search code examples
kotlindata-class

Why doesn't Kotlin implicitly assign null values nullable fields in a data class constructor?


Given a data class with a nullable field, why can't I construct it by only passing the non-nullable fields ?

I have already seen this related question. What is preventing Kotlin from implicitly assigning null to the nullable fields ?

data class Blah(val id: Int, val name: String?)

val x = Blah(id = 2) // Complains I didn't pass a name ???

Solution

  • No technical reason is preventing Kotlin to be designed so that nullable types in the parameter list of primary constructors get a default null value, but still, it is not designed this way.

    Here is a possible explanation as to why.

    At the end of the day, the (...) you put after the data class name is first and foremost, a parameter list, for the primary constructor. Yes, you can declare properties there, but it is still a primary constructor parameter list. Treating this particular kind of parameter list to behave differently from other parameter lists would make Kotlin a little more inconsistent. Would you want plain old function parameter lists to do this too?

    fun foo(number: Int?) { ... }
    
    // Should you be able to call foo like this?
    foo()
    

    Even if you would like every parameter list to behave like this, what if you want to opt out of this for certain functions? Perhaps you wrote a function/data class and you really want callers to explicitly pass null to one of its parameters, in order to e.g. make sure the caller is making a conscious choice. There would need to be extra complexity (e.g. a new annotation like @NoDefaultNull, or a new keyword like required - the design of this can be discussed for ages) to allow you to opt out of this behaviour.

    Making primary constructors' parameter lists work like any other parameter list is the simplest option. If you want the nullable parameters optional, just add = null like you would with any other parameter list.

    If you have another better idea, feel free to submit a ticket to YouTrack.