mgrazianodecastro
01/19/2023, 6:21 PMhfhbd
01/19/2023, 6:22 PMCasey Brooks
01/19/2023, 6:22 PM.toList()
instead. If you cast it, someone else could cast it back to a mutable list and modify it in a place where it should be treated as read-onlyVampire
01/19/2023, 6:23 PMList
as return typeCasey Brooks
01/19/2023, 6:26 PMArrayList
. But regardless, even if the result of toList()
is an instance of ArrayList
(which implements MutableList
), it’s still a separate instance, and thus prevents changes to the original listmgrazianodecastro
01/19/2023, 6:26 PMCasey Brooks
01/19/2023, 6:27 PM.add()
does not return a listmgrazianodecastro
01/19/2023, 6:28 PMKlitos Kyriacou
01/19/2023, 6:31 PMtoList()
, then (if you're on the JVM) you can wrap it using Collections.unmodifiableList(colors) as List<Color>
Joffrey
01/19/2023, 9:56 PMbuildList { ... }
if you temporarily need a mutable list during construction but then want the result as List
. That said, in your specific case you should consider List(10) { Color.Black } + Color.Transparent
Vampire
01/19/2023, 9:58 PMKlitos Kyriacou
01/19/2023, 10:03 PMArrayList
that it is, and modify it. Though I don't usually worry about such things. If a programmer that uses my API wants to be malicious, they can be malicious in many more ways than casting a List
to a MutableList
.Joffrey
01/20/2023, 11:27 AMlistOf(Color.Transparent) + List(10) { Color.Black } + Color.Transparent
. I guess buildList
would be the best approach here.Klitos Kyriacou
01/20/2023, 11:34 AMvalues()
method returns a newly created array each time it's called. This is because in Java and Kotlin there are no read-only arrays, and the compiler doesn't prevent accidental modification of the returned array's values. But for List, that's different.Joffrey
01/20/2023, 11:38 AMan enum's values() method returns a newly created array each time it's calledBut we're not the ones making defensive copying in business code. In Kotlin we usually deal with lists for this reason. Also incidentally the enum entries will soon be lists 😄
Klitos Kyriacou
01/20/2023, 11:40 AM