简体   繁体   中英

How to determine the initialization order of Kotlin vals?

Suppose I have a val that is defined as follows

import a.b.FIRSTNAME;
val FULLNAME = "$FIRSTNAME/aaron"

And this FIRSTNAME is defined in ab as

val FISTNAME = "LINCON";

I will find that sometimes FULLNAME takes the value of null/aaron in the process of using it.

As I answered here , the order in which Kotlin initialises global properties is unspecified and platform dependent. 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.

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:

val firstName = "LINCON";
val fullName get() = "$firstName/aaron"

Alternatively, I think adding const will also work. 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM