Companion object initialization weirdness

I’m seeing something very weird.

sealed class Foo {
    object Bar: Foo()
    object Baz: Foo()

    companion object {
        val DEFAULT: Foo = Bar
    }
}

// in another class
val value = Foo.DEFAULT // <-- value will be *null*!!

When I try to get Foo.DEFAULT in another class early on in the app’s lifetime, it returns null instead of Bar.

This is an Android app if it makes any difference.

2 Likes

The companion object and its fields are initialized before memebers. Hence when DEFAULT is initialized Bar isn’t.
You get have a getter on DEFAULT or move Bar and Baz inside the companion as well.

2 Likes

I don’t have Android Studio, but in normal console Kotlin app this works as intended.

Adding a getter fixed it.

val DEFAULT: Foo
    get() = Bar

I think when you run it in the console it loads the sealed class before the main function is executed.