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?
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
CLOVIS
01/11/2023, 8:29 AM
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
ephemient
01/11/2023, 8:32 AM
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.