Make data class members immutable by default

Most of the times the data class members I use are immutable.
As Kotlin function parameters are immutable, data class members should be also by default, especially if you do lots of functional paradigm.

data class User(firstName: String, lastName: String, age: Int)
is much cleaner than
data class User(val firstName: String, val lastName: String, val age: Int).

I am not saying that mutable types are prohibited but leaving out the val should be also possible.

Just my opinion.

3 Likes

Coming from Scala I had the same thought initially. Maybe I simply get used to the Kotlin syntax, but as a benefit I see that it is obvious that you have a val and not a simple (and in this case useless) constructor parameter. It is consistent at the cost of a little bit more code.

7 Likes

In my opinion being consistent is more important than being concise.

It’s still valid Kotlin code to have something like this:

data class User(val fullName: String) {
    constructor (firstName: String, 
                 lastName: String) : this("$firstName $lastName")
}
4 Likes

It’s great if we can make val by default. Our class can be more concise.
Rust is designed in that way: Mutable Reference in Rust. Before moving to understanding the… | by vikram fugro | Medium

Constructor params, and all other functions, are already val by default. The only time you can make them var is when declaring them as member properties.

The val in a data class constructor is used to make class properties.

Having to declare val or var keeps things consistent with normal classes. A behavioral change for data classes would be confusing and mean you can no longer simply add/remove “data” from your class to make your class a data class.

Even if the proposal was expanded to include all classes (not just data classes) treating every constructor variable as a val member property, you’re only saving a small amount of characters. Readabilityy != Concision.

Technically this isn’t a breaking change as data classes are required to declare all primary contractor parameters as member properties. As long as the old, and IMHO more clear way of doing things was still allowed.

TL:DR
All parameters are already val by default. IMO, making data classes have such a core difference to the way member properties are declared compared to normal classes would likely cause more confusion and pain than any value saved by typing a few less characters.

2 Likes