可变和不可变集合类是相同的 kotlin

Mutable and immutable collection classes are the same kotlin

提问人: 提问时间:7/13/2020 更新时间:7/13/2020 访问量:319

问:

使用反射来调查集合类时,同一类型的可变类和不可变类在引用上是相等的。

为什么会这样?

    @Test
    fun demonstrate_mutableAndImmutableClassesAreTheSame() {
        println("(MutableIterable::class === Iterable::class) = ${(MutableIterable::class === Iterable::class)}")
        println("(MutableCollection::class === Collection::class) = ${(MutableCollection::class === Collection::class)}")
        println("(MutableList::class === List::class) = ${(MutableList::class === List::class)}")
        println("(MutableSet::class === Set::class) = ${(MutableSet::class === Set::class)}")
        println("(MutableMap::class === Map::class) = ${(MutableMap::class === Map::class)}")
        println("(MutableMap.MutableEntry::class === Map.Entry::class) = ${(MutableMap.MutableEntry::class === Map.Entry::class)}")
    }

指纹

(Iterable::class === MutableIterable::class) = true
(Collection::class === MutableCollection::class) = true
(List::class === MutableList::class) = true
(Set::class === MutableSet::class) = true

科特林 反射 收集 JVM的 可变

评论

1赞 Animesh Sahu 7/13/2020
在平台 (JVM) 中,两者是相同的。您不能重载这些类型,因为它们在运行时也是相同的,请参阅此处。文档在这里也提到了这一点
0赞 Salem 7/13/2020
可能值得注意的是,仅当作为依赖项包含在内时,这才是正确的(否则所有结果都是 。这也不适用于 Kotlin/JS(大概也是原生的,但我还没有测试过。kotlin-reflectfalse

答:

0赞 Animesh Sahu 7/13/2020 #1

Collection并且映射到相同的 java.util.Collection 类(映射类型),因此从 JVM 的 POV(在运行时编译后)来看它们是相同的。MutableCollection

如果你反编译你编写的代码,你会得到这个(我使用 Intellij 生成的 Kotlin 字节码反编译它):

科特林:

fun demonstrate_mutableAndImmutableClassesAreTheSame() {
    println("(MutableCollection::class === Collection::class) = ${(MutableCollection::class === Collection::class)}")
}

爪哇岛:

import kotlin.jvm.internal.Reflection;

// class declaration
public static final void demonstrate_mutableAndImmutableClassesAreTheSame() {
    String var0 = "(MutableCollection::class === Collection::class) = " + (Reflection.getOrCreateKotlinClass(Collection.class) == Reflection.getOrCreateKotlinClass(Collection.class));
    boolean var1 = false;
    System.out.println(var0);
}

引用: