Hello, I have a question about using Java 9's imm...
# stdlib
h
Hello, I have a question about using Java 9's immutable collection factory functions in Kotlin. I want to make an immutable list (as opposed to a read-only view of a list), mainly for defensive purposes, but when I use
List.of
IntelliJ warns me that it "should be replaced with [the] Kotlin function"
listOf
. If I understand correctly, these two functions are actually very different; is there something I am missing? Is this a false positive?
e
https://youtrack.jetbrains.com/issue/KTIJ-12411 it is an intentional part of Java-to-Kotlin conversion
also, runtime-enforced immutability instead of type-enforced is not necessary in good Kotlin code, and since the Kotlin compiler doesn't know about Java semantics, it allows you to write
Copy code
val x: MutableList<Int> = List.of()
whereas
listOf()
would be rejected
c
What are you trying to defend against? The compiler will stop mutation attempts to
listOf
. Someone running code in the same JVM as you will be able to edit any value if they really want to.
e
I could understand
Collections.unmodifiableList()
etc. being used defensively if interoperating with Java code, and
List.of()
is similar to
unmodifiableList(listOf())
(with a few additional unique behaviors). if that really is your situation, then ignore the inspection. but if you're just in Kotlin, I would stick with the Kotlin functions.