Drop val from data classes


#1

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.


#2

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.


#3

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.


#4

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.


#5

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.