Home > Net >  Companion object is not accessiable from Java code?
Companion object is not accessiable from Java code?

Time:09-22

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.

CodePudding user response:

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();

CodePudding user response:

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.

CodePudding user response:

you just need to add JvmStatic annotation

companion object{
    @JvmStatic
    val x=10
}
  • Related