gpt4 book ai didi

kotlin - EnumClass.values()在Kotlin中如何工作?

转载 作者:行者123 更新时间:2023-12-02 12:48:18 25 4
gpt4 key购买 nike

EnumClass.values()在Kotlin中如何工作?

我的意思是,它将每次创建新的Array,还是被静态评估为惰性,还是其他?

最佳答案

虽然不是100%肯定,但我假设Enum.values()方法是由编译器生成的: Kotlin (以及 Java ):

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.



JLS:
/**
* Returns an array containing the constants of this enum
* type, in the order they're declared. This method may be
* used to iterate over the constants as follows:
*
* for(E c : E.values())
* System.out.println(c);
*
* @return an array containing the constants of this enum
* type, in the order they're declared
*/
public static E[] values();

每次,此方法 返回新数组

关键是在 Java 中数组不能恒定:它的值可以修改,因此您不能共享同一数组,而必须在每次访问时都给一个新数组,以确保该数组尚未被使用。改变了。

简单测试:
enum class MyEnum { CAT, DOG }

val a = MyEnum.values()
val b = MyEnum.values()

println("${a === b}") // >>> false

a[0] = MyEnum.DOG
println(a.joinToString()) // >>> [DOG, DOG]
println(MyEnum.values().joinToString()) // >>> [CAT, DOG]

关于kotlin - EnumClass.values()在Kotlin中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com