How can I refer to companion objects from Java?
The companion object in Kotlin has static fields and support methods for interacting with Java, so you can essentially treat them like a static class if you've annotated them correctly (using @JvmStatic and @JvmField). So:
class C {
companion object {
@JvmStatic fun foo() {}
fun bar() {}
}
}
foo can be obtained from Java as a static function. The bar can't.
C.foo(); // works fine
C.bar(); // error: not a static method
C.Companion.foo(); // instance method remains
C.Companion.bar(); // the only way it works
You can do the same with fields, except using JvmField
class Key(val value: Int) {
companion object {
@JvmField val COMPARATOR: Comparator<Key> = compareBy<Key> { it.value }
}
}
Then:
// Java
Key.COMPARATOR.compare(key1, key2);
// public static final field in Key class
You can also use const.
// file: Example.kt
object Obj {
const val CONST = 1
}
class C {
companion object {
const val VERSION = 9
}
}
const val MAX = 239
In Java:
int c = Obj.CONST;
int d = ExampleKt.MAX;
int v = C.VERSION;
See Java's Kotlin interop in the documentation for full details on the details (all examples from copy anyway).
I recommend knowing (and using) the JvmStatic and JvmField annotation well if you want to interact with Java frequently, as they are indeed critical to smoothing Kotlin's interaction with Java.
source to share
Good! If you have something like:
class MyKotlinClass {
companion object {
val VAR_ONE = 1
val VAR_TWO = 2
val VAR_THREE = 3
fun printOne() {
println(VAR_ONE)
}
}
}
you can access the fields from your Java class this way
public class MyJavaClass {
private void myMethod(){
MyKotlinClass.Companion.getVAR_ONE();
//The same for methods
MyKotlinClass.Companion.printOne();
}
}
source to share