我有一个非常基本forEach的代码,如下面的代码。
val array = arrayOf(1, 2)
val list = listOf(1, 2)
array.forEach(::println)
list.forEach(::println)
但是,如果用Java反编译,则forEach根据Array和List的不同,实现方法不同。
Integer[] array = new Integer[]{ 1, 2 };
List list = CollectionsKt.listOf(new Integer[]{ 1, 2 });
Integer[] var4 = array;
int var5 = array.length;
int p1;
for(p1 = 0; p1 < var5; ++p1) {
Object element $iv = var4[p1];
int p1 =((Number) element $iv).intValue();
System.out.println(p1);
}
Iterable $this$forEach$iv = (Iterable)list;
Iterator var11 = $this$forEach$iv.iterator();
while(var11.hasNext()) {
Object element $iv = var11.next();
p1 = ((Number) element $iv).intValue();
System.out.println(p1);
}
通过检查 的实现方法forEach,两者都是以相同的for (element in this) action(element)方法实现的。
public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
我一直在寻找 Array 和 List 之间的区别,以找出为什么 Array 和 List 的实现方式不同in,但我没有找到与in关键字相关的任何内容。为什么 Array 和 List 的 in 实现看起来不同?