Drop val from data classes

I think that data classes should allow fields to be declared without needing val or var, in which case it would default to val.

I would assume (correct me if you think otherwise) that the vast majority of data classes would use val and not var anyway, and then it’s just extra noise.

3 Likes

I feel this would make things more concise but less readable.

Image

IMHO, val and var are not extra noise. Having val and var in data classes means their behavior will match what’s expected of non data classes as well.

5 Likes

Perhaps.

If they were both used a lot I’d agree.

Does anyone make var data classes? Maybe they do but none of the people I work with do.

1 Like

In rare cases I had to use data classes with mutable fields. Example of this are classes used for JAXB unmarshalling :slight_smile:

To assure that collections are always non-nullable I had to apply this trick:

@XmlRootElement
data class Root(
	@field:XmlElement(name = "number")
	var numbers: SortedSet<Long>
) {
	private fun afterUnmarshal(unmarshaller: Unmarshaller, parent: Any) {
		numbers = numbers ?: sortedSetOf()
	}
}

Ideally I would more prefer that there would be a syntax to make setters of primary constructor properties private.

Doesn’t look like anyone has mentioned that without val or var, a constructor parameter doesn’t get a backing field. I think it would be super confusing to have the lack of val or var mean different things when you do or don’t use the data keyword on a class.

Yes, the Android Room ORM required (or at least until the most recent release) that properties be var because they had to be late initialized in some cases.

1 Like

@joshfriend in a data class, you have to include val or var right, you can’t “leave them out”.
So I’m just saying instead of doing this

data class Person(val name: String, val age: Int)

also allow this as an equiv

data class Person(name: String, age: Int)

You can still do

data class Person(var name: String, var age: Int)

Given that (my guess only) that 98% of people use vals here for immutability, then defaulting to that just saves a bunch of noise (imo). Plus it’s 100% backwards compatible.

1 Like