[英]Order of init calls in Kotlin Array initialization
In the constructor of an Array is there a guarantee that the init function will be called for the indexes in an increasing order? 在Array的构造函数中是否保证将以递增的顺序为索引调用init函数?
It would make sense but I did not find any such information in the docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/-init-.html#kotlin.Array%24 %28kotlin.Int%2C+kotlin.Function1%28%28kotlin.Int%2C+kotlin.Array.T%29%29%29%2Finit 这是有道理的,但我没有在文档中找到任何此类信息: https ://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/-init-.html#kotlin.Array%24% 28kotlin .INT%2C + kotlin.Function1%28%28kotlin.Int%2C + kotlin.Array.T%29%29%29%2Finit
There is no guarantee for this in the API. API中无法保证这一点。
TLDR: If you need the sequential execution, because you have some state that changes see bottom. TLDR:如果您需要顺序执行,因为您有一些更改的状态请参见底部。
First lets have a look at the implementations of the initializer: 首先让我们看一下初始化程序的实现:
Native: It is implemented in increasing order for Kotlin Native . Native:它按照Kotlin Native的递增顺序实现。
@InlineConstructor
public constructor(size: Int, init: (Int) -> Char): this(size) {
for (i in 0..size - 1) {
this[i] = init(i)
}
}
JVM : Decompiling the Kotlin byte code for JVM :为Kotlin字节代码重新编译
class test {
val intArray = IntArray(100) { it * 2 }
}
to Java in Android Studio yields: 到Android Studio中的Java产生:
public final class test {
@NotNull
private final int[] intArray;
@NotNull
public final int[] getIntArray() {
return this.intArray;
}
public test() {
int size$iv = 100;
int[] result$iv = new int[size$iv];
int i$iv = 0;
for(int var4 = result$iv.length; i$iv < var4; ++i$iv) {
int var6 = false;
int var11 = i$iv * 2;
result$iv[i$iv] = var11;
}
this.intArray = result$iv;
}
}
which supports the claim that it is initialized in ascending order. 它支持声明它按升序初始化。
Conclusion: It commonly is implemented to be executed in ascending order. 结论:它通常被实现为按升序执行。
BUT: You can not rely on the execution order, as the implementation is not guaranteed by the API. 但是:您不能依赖执行顺序,因为API无法保证实现。 It can change and it can be different for different platforms (although both is unlikely). 它可以改变,并且对于不同的平台可以是不同的(尽管两者都不太可能)。
Solution: You can initialize the array manually in a loop, then you have control about the execution order. 解决方案:您可以在循环中手动初始化阵列,然后您可以控制执行顺序。 The following example outlines a possible implementation that has a stable initialisation with random values, eg for tests. 以下示例概述了具有随机值的稳定初始化的可能实现,例如用于测试。
val intArray = IntArray(100).also {
val random = Random(0)
for (index in it.indices) {
it[index] = index * random.nextInt()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.