Kotlin - Is it possible to initialize a companion object before an init block in a class?

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

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) } } } 

and a call to printAllStatics throws a null pointer exception.

+6
source share
2 answers

Property initializers and init blocks are executed in exactly the same order in which they are placed in the body of the class / object. Here is 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") } } 

He will print 1 2 3 4 .

So, in your case, replacing two declarations in a companion object enough:

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

Just change the order of the lines:

 @JvmField val foo = mutableListOf<A>() @JvmField val STATIC = A("hi") 

Before using foo in A , but it was not initialized.

+3
source

Source: https://habr.com/ru/post/1011883/


All Articles