In the following Kotlin code snippet:
fun main() {
val list = listOf(1, 2, 3)
println(list is MutableList<Int>) // true
}
I expect that list
of type List<Int>
should not be considered a MutableList<Int>
, but the compiler outputs:
Condition 'list is MutableList' is always true.
I understand that MutableList
is a subtype of List
. Is this some form of downcasting? How exactly does the is
operator work in this context?
I've read the documentation on the is
operator, but I still can't find an explanation for this specific behavior:
I'm also interested in diving into the source code of the is
operator, but it's hard for me to find it in https://github.com/JetBrains/kotlin.
Kotlin Version: 2.0.10
Kotlin uses Java collection classes, which only have a single List interface containing both read and mutation methods. Compile-time references to List and MutableList are both compiled to java.util.List references. You can see the detailed answer here, 1 user asked a similar question to yours: https://stackoverflow.com/a/52591274/20536350