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.

2 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.

6 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")
}
2 Likes