https://kotlinlang.org logo
#announcements
Title
# announcements
g

geatmo

09/13/2017, 1:30 PM
a few days ago somewhere in here I learned of this nice pattern to create a populated list:
val myList = List(3) { it }
which, as the documentation states, creates a read-only list.. but as far as I can see, this list only appears to really be read-only, as I am able to do this:
(myList as MutableList).clear()
and the list will get modified.. so for actually immutable lists, should I better stick to keep using
listOf()
instead?
okay, scratch that.. although
clear()
is not working when using
listOf()
, something like
set()
is.. so I guess I'm stuck with "I gave you a immutable list reference.. please don't try to cast it to being mutable" with both of those methods..
k

karelpeeters

09/13/2017, 5:11 PM
The distinction doesn't exist at runtime, indeed. If you really need it to be immutable, maybe for security reasons, use
Collections.immutableList
.
g

geatmo

09/14/2017, 8:56 AM
Thanks. Yeah, I might end up using it. Although at this point it's not that critical. I'd just would have like for my API to be more robust, as everything else in my data classes is actually read-only, without a way around it.
2 Views