https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Loney Chou

01/23/2023, 2:46 PM
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

Sam

01/23/2023, 2:49 PM
It’s in development 👍K
👍 1
l

Loney Chou

01/23/2023, 3:16 PM
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

Sam

01/23/2023, 3:20 PM
There is an open issue for that I think: https://youtrack.jetbrains.com/issue/KT-9959
l

Loney Chou

01/23/2023, 3:26 PM
Seems like this problem doesn't attract much attention.
v

Vampire

01/23/2023, 4:44 PM
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

Klitos Kyriacou

01/24/2023, 11:12 AM
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

Sam

01/24/2023, 11:30 AM
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

Klitos Kyriacou

01/24/2023, 11:32 AM
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

Sam

01/24/2023, 11:33 AM
Yeah, after I wrote “even worse” I started to change my mind, I think your example is more insidious
l

Loney Chou

01/24/2023, 2:29 PM
Same preference, listOf should be somehow unmodifieable, just like List.of from java.
5 Views