Copy List in data class constructor


#1

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


#2

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.


#3

How about calling toList on the parameters by default?


#4

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.


#5

I agree, thank you.


#6

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


#7

Doing the copy is kind of problematic with data classes


#8

@voddan What do you mean?


#9

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()
}