Loney Chou
01/23/2023, 2:46 PMlistOf
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?Sam
01/23/2023, 2:49 PMLoney Chou
01/23/2023, 3:16 PMlistOf()
and listOf(1)
both returns immutable list, while listOf(1, 2)
returns a read-only but mutable list. This is a bit unsafe.Sam
01/23/2023, 3:20 PMLoney Chou
01/23/2023, 3:26 PMVampire
01/23/2023, 4:44 PMList
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.Klitos Kyriacou
01/24/2023, 11:12 AMList
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:
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".Sam
01/24/2023, 11:30 AMjava.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.Klitos Kyriacou
01/24/2023, 11:32 AMval list = listOf(1, 2, 3, 4, 5, 6)
I like to be able to rely on list
being unchanged.Sam
01/24/2023, 11:33 AMLoney Chou
01/24/2023, 2:29 PM