Is it possible to initialize an companion object before the init block in a Kotlin class? If so, how? If not, is there a way to accomplish the same thing.

I have the following scenario,

class A(val iname: String) {
  init {
    foo.add(this)
  }

  companion object B {
    @JvmField val STATIC = A("hi")
    @JvmField val foo = mutableListOf<A>()   
  }

  fun printAllStatics() {
    for (a in foo) {
      print(a.iname)
    }
  }
}

并且调用printAllStatics会导致空指针异常.

推荐答案

The property initializers and init blocks are executed in exactly the same order in which they are placed in a class/object body. Here's an example:

companion object B {
    init {
        print("1 ")
    }

    @JvmField val foo = mutableListOf<A>().apply { print("2 ") }
    @JvmField val bar = mutableListOf<A>().apply { print("3 ") }

    init {
        print("4")
    }
}

它将打印1 2 3 4

So, in your case, swapping the two declarations in the companion object is enough:

companion object B {
    @JvmField val foo = mutableListOf<A>()   
    @JvmField val STATIC = A("hi")
}

Kotlin相关问答推荐

DataSnapshot.getValue()未记录的奇怪行为

在Kotlin Jetpack中重用下拉菜单

用浮点数或十进制数给出错误答案的阶乘计算

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

如何编写带有依赖项的自定义Kotlin串行化程序?

捕捉异常是Kotlin协程中的反模式吗?

在Kotlin中的嵌套when语句中,else块是强制性的吗?

从 Kotlin 的父类获取函数注解

Kotlin中是否可以混合使用推断和显式的通用类型参数?

在 kotlin 中使具体化字段可选

为什么会出现Kotlin.Unit错误以及如何修复它?

根据字符串值动态过滤数组列表 - kotlin

parallelStream()和asSequence().asStream().parallel()之间的区别

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

runOnUiThread 没有调用

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

无法在Kotlin中使用argb color int值?

如何在使用Koin DI的活动之间共享同一个ViewModel实例?

在 sharedPref.getString 中有一个默认值有什么意义?