Copy List in data class constructor

Hi,

when I use data class, with a List<> parameter, is there a way to ensure that it’s not passed a MutableList<>, which can be changed after being passed to my data class?

Thanks
Fabian

1 Like

No, there is no such way. Even if Kotlin had any support for that, your constructor would be accessible to Java code, which could pass any List instance to it.

How about calling toList on the parameters by default?

This would be quite surprising in terms of performance, and also wouldn’t work when you had a generic data class where a specific instance has a List as an argument.

I agree, thank you.

You would want to use something like a guava ImmutableList there, or do the copy yourself.

Doing the copy is kind of problematic with data classes

@voddan What do you mean?

It was a reply to

since the syntax of data classes does not allow for operations on initialisation like normal classes do:

class A(list: List) {
    val list = list.toList()
}