`listOf` returns a read-only list on kotlin side, ...
# getting-started
l
listOf
returns a read-only list on kotlin side, but on JVM it's actually a
java.util.Arrays.ArrayList
which is still mutable. Why doesn't kotlin team create a real immutable list type?
s
It’s in development 👍K
👍 1
l
I mean, on JVM
listOf()
and
listOf(1)
both returns immutable list, while
listOf(1, 2)
returns a read-only but mutable list. This is a bit unsafe.
s
There is an open issue for that I think: https://youtrack.jetbrains.com/issue/KT-9959
l
Seems like this problem doesn't attract much attention.
v
The main point probably is, that someone with evil energy can almost always somehow circumvent the immutability if he really wants to. The read-onlyness of
List
is more a hint to the user to not modify the list but only use it read-only or create a new mutable list for mutating. This way you save the extra effort to make things immutable and defensively copy things continuously.
👍 1
k
I think the "danger" here is that you might pass a
List
to a third-party Java library method that takes a
List
and modifies it because you didn't realise that you should be passing a mutable list. Example:
Copy code
fun main() {
    val list = listOf(1, 2, 3, 4, 5, 6)
    java.util.Collections.reverse(list)
    println(list)
}
The above may issue an IDE warning (if you're set things right), but it compiles and runs "just fine".
s
Right, or even worse,
Copy code
java.util.Collections.replaceAll(listOf("foo"), "foo", "bar")
which compiles fine (without even a warning) but fails at runtime 😱. Methods like
reverse
,
shuffle
etc. get lucky because they just happen to be a no-op for lists of size 0 and 1, which are the ones Kotlin makes immutable.
k
I'd rather have it fail with an exception at runtime than it being modified unexpectedly. When I see
val list = listOf(1, 2, 3, 4, 5, 6)
I like to be able to rely on
list
being unchanged.
s
Yeah, after I wrote “even worse” I started to change my mind, I think your example is more insidious
l
Same preference, listOf should be somehow unmodifieable, just like List.of from java.