Kotlin阵列初始化中的初始化调用顺序 [英] Order of init calls in Kotlin Array initialization

查看:86
本文介绍了Kotlin阵列初始化中的初始化调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数组的构造函数中,是否可以保证索引的递增顺序将调用init函数?

In the constructor of an Array is there a guarantee that the init function will be called for the indexes in an increasing order?

这是有道理的,但是我没有在文档中找到任何此类信息: 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

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

推荐答案

API中对此没有保证.

There is no guarantee for this in the API.

TLDR:如果需要顺序执行,因为您有一些状态需要更改,请参见底部.

TLDR: If you need the sequential execution, because you have some state that changes see bottom.

首先让我们看一下初始化程序的实现:

First lets have a look at the implementations of the initializer:

本机:对于 JVM :反编译

class test {
    val intArray = IntArray(100) { it * 2 }
}

在Android Studio中使用Java产生的收益:

to Java in Android Studio yields:

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.

但是::您不能依赖执行顺序,因为API不能保证实现.它可能会发生变化,并且对于不同的平台可能会有所不同(尽管两者均不太可能).

BUT: You can not rely on the execution order, as the implementation is not guaranteed by the 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, e.g. for tests.

val intArray = IntArray(100).also {
    val random = Random(0)
    for (index in it.indices) {
        it[index] = index * random.nextInt()
    }
}

这篇关于Kotlin阵列初始化中的初始化调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆