[英]How to determine the initialization order of Kotlin vals?
Suppose I have a val that is defined as follows假设我有一个定义如下的 val
import a.b.FIRSTNAME;
val FULLNAME = "$FIRSTNAME/aaron"
And this FIRSTNAME
is defined in ab as而这个FIRSTNAME
在 ab 中定义为
val FISTNAME = "LINCON";
I will find that sometimes FULLNAME takes the value of null/aaron
in the process of using it.我会发现有时候FULLNAME在使用的过程中会取null/aaron
的值。
As I answered here , the order in which Kotlin initialises global properties is unspecified and platform dependent.正如我在这里回答的那样,Kotlin 初始化全局属性的顺序未指定且取决于平台。 This is especially annoying when you have multiple files with properties that depend on each other.当您有多个属性相互依赖的文件时,这尤其令人讨厌。
See this Kotlin/Native bug report , and this Kotlin/JS bug report about people finding the initialisation behaviour across multiple files confusing.请参阅这个 Kotlin/Native 错误报告和这个 Kotlin/JS 错误报告,关于人们发现跨多个文件的初始化行为令人困惑。
In any case, you should avoid this kind of "top level properties depending on each other".无论如何,您应该避免这种“相互依赖的顶级属性”。 And in this particular case, you can rewrite FULLNAME
using a getter:在这种特殊情况下,您可以使用 getter 重写FULLNAME
:
val firstName = "LINCON";
val fullName get() = "$firstName/aaron"
Alternatively, I think adding const
will also work.或者,我认为添加const
也可以。 The expressions will now be evaluated at compile time by the compiler, and inlined to whenever you use them.现在,编译器将在编译时评估表达式,并在您使用它们时内联。
const val FIRST_NAME = "LINCON";
const val FULL_NAME = "$FIRST_NAME/aaron"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.