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.
Asked
Active
Viewed 1,289 times
0
3 Answers
4
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();

Joffrey
- 32,348
- 6
- 68
- 100
1
you just need to add JvmStatic annotation
companion object{
@JvmStatic
val x=10
}

Saurabh Dhage
- 1,478
- 5
- 17
- 31
1
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.

Agent_L
- 4,960
- 28
- 30