Why Companion object is not accessible from Java code?

1.6k Views Asked by At

As we know Kotlin and Java are inter-operable. When I try to access Java static variable inside Kotlin code it works, but when I try to access companion object in Java, it does not work.

3

There are 3 best solutions below

0
On BEST ANSWER

you just need to add JvmStatic annotation

companion object{
    @JvmStatic
    val x=10
}
0
On

You need to specify Companion explicitly. Java:

    MyFragment newFragment = MyFragment.Companion.newInstance();

That's because companion's methods are NOT static. The companion is static, but its methods are regular, instance methods.

0
On

There are no statics in Kotlin per se.

Properties of the companion object can be accessed in Java by explicitly referring to the Companion instance:

class MyKotlinClass {
    companion object {
        val someProperty = 42
    }
}

From Java:

int someProperty = MyKotlinClass.Companion.getSomeProperty();

You can also force Kotlin to output bytecode with static members (for Java) by using a JVM-specific annotation:

class MyKotlinClass {
    companion object {
        @JvmStatic
        val someProperty = 42
    }
}

From Java:

int someProperty = MyKotlinClass.getSomeProperty();