[Solved] Why is a object can be null

Due to KT-8970, I wrap the line with lazy. And it’s ok.


The Inflate is null in debugger, but it’s a object. Why is it?

kotlin("jvm") version "1.5.21"
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2")

https://github.com/SettingDust/bilive-danmaku/blob/main/src/main/kotlin/io/github/settingdust/bilive/danmaku/Packet.kt#L310

Fields of the companion object are initialized before other objects contained in a class.

1 Like

But the others are initialized. Besides the first.

Ok, that’s weird.

Why don’t you just put those objects in the companion object? Is there some difference whether they’re inside the class as they are now VS being in the companion object?

1 Like

XXX.Companion.XXX VS XXX.XXX

1 Like

This should only apply to Java code, though. In Kotlin, you can use companion object’s properties with just ClassName.property:
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS41LjIxIiwiY29kZSI6ImZ1biBtYWluKCkge1xuICAgIHByaW50bG4oQS5jb21wYW5pb25Qcm9wZXJ0eSlcbn1cblxuY2xhc3MgQSB7XG4gICAgXG4gICAgY29tcGFuaW9uIG9iamVjdCB7XG4gICAgICAgIHZhbCBjb21wYW5pb25Qcm9wZXJ0eSA9IDQyXG4gICAgfVxufSIsInBsYXRmb3JtIjoiamF2YSIsImFyZ3MiOiIifQ==

2 Likes

You don’t need to call it like XXX.Companion.XXX in Kotlin. And if you call it from Java, you can annotate your member with @JvmStatic, so in Java you can call it also like XXX.XXX.

2 Likes

https://pl.kotl.in/mULr3GAxG
cc: @luhtonen

Ah I see. It seems I had misunderstood your actual problem. It’s about the object declarations in the Companion, not properties. In that case I agree it’s kinda confusing. I guess lazy is the best you can do for now.

2 Likes