Top level non-null variables are null

Hello.

I’m facing a really strange issue in kotlin.

given that top level variables in kotlin, declared outside any classes or other scopes are initialized with any order, but it is guaranteed that when you access a variable it is initialized, i have something like this:

val classVariableExp =
    variableName["variableName"] + spaces + ":" + spaces + variableName["variableType"]

which results in this error

Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.momid.compiler.CFKt.cf(CF.kt:30)
	at com.momid.compiler.CFKt.<clinit>(CF.kt:23)
	at com.momid.compiler.ParserKt.<clinit>(Parser.kt:43)
	at com.momid.compiler.ClassKt.<clinit>(Class.kt:8)
Caused by: java.lang.NullPointerException: Cannot invoke "kotlin.Lazy.getValue()" because "<local0>" is null
	at com.momid.compiler.ParserKt.getComplexExpression(Parser.kt:60)
	at com.momid.compiler.StatementKt.<clinit>(Statement.kt:18)
	... 4 more

naturally it must not be null but it is. i also tried using lazy delegation to avoid possible circular dependency issues between the top level variables and now i’m getting this:

Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.momid.compiler.CFKt.cf(CF.kt:30)
	at com.momid.compiler.CFKt.<clinit>(CF.kt:23)
	at com.momid.compiler.ParserKt.<clinit>(Parser.kt:43)
	at com.momid.compiler.ClassKt.<clinit>(Class.kt:8)
Caused by: java.lang.NullPointerException: Cannot invoke "kotlin.Lazy.getValue()" because "<local0>" is null
	at com.momid.compiler.ParserKt.getComplexExpression(Parser.kt:60)
	at com.momid.compiler.StatementKt.<clinit>(Statement.kt:19)
	... 4 more

searching for Cannot invoke "kotlin.Lazy.getValue()" because "<local0> on the internet you’ll find absolutely nothing.

so my main question is can you have top level variables defined in different files in kotlin reference each other in any order? if yes then what is the error i’m getting and how to fix it.

thanks.

Can you show the rest of the code? Especially the part that uses lazy delegation

sure. here it is.

image

okay, can you try defining:

val classVariableExp by lazy {
    variableName["variableName"] + spaces + ":" + spaces + variableName["variableType"] 
}

so that it is lazy as well

1 Like

made all the involved top-level variables lazy and it seems to work. still not sure why it cannot handle variable dependencies without making them lazy and their values being null as a result.
thank you btw!