Home > Back-end >  How to determine the initialization order of Kotlin vals?
How to determine the initialization order of Kotlin vals?

Time:08-18

Suppose I have a val that is defined as follows

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

And this FIRSTNAME is defined in a.b as

val FISTNAME = "LINCON";

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

CodePudding user response:

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"
  • Related