提问人: 提问时间:7/13/2020 更新时间:7/13/2020 访问量:319
可变和不可变集合类是相同的 kotlin
Mutable and immutable collection classes are the same kotlin
问:
使用反射来调查集合类时,同一类型的可变类和不可变类在引用上是相等的。
为什么会这样?
@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
答:
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);
}
引用:
评论
kotlin-reflect
false