I have a mixed project, Java
and Kotlin
classes, and I want to know how I can refer to companion objects
from my Java
classes.
A companion object in Kotlin has static backing fields and methods in order to interop with Java, so you can essentially treat them like a static class, if you have annotated them correctly (using @JvmStatic and @JvmField). So:
class C {
companion object {
@JvmStatic fun foo() {}
fun bar() {}
}
}
foo can be accessed from Java like a static function. Bar cannot.
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 you use 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;
For the nitty-gritty details, see Java to Kotlin interop in the documentation (examples are all copy-pasted from there anyway).
I recommend getting to know (and using) the JvmStatic and JvmField annotation well, if you want to interop with Java often, since they're really crucial to smooth Kotlin to Java interaction.
int d = CKt.MAX
, are I'm right? –
Nacre Okay! 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 could access the fields from your Java class in this way
public class MyJavaClass {
private void myMethod(){
MyKotlinClass.Companion.getVAR_ONE();
//The same for methods
MyKotlinClass.Companion.printOne();
}
}
This is the Kotlin class with companion object.
class A {
companion object {
@JvmStatic fun foo() {}
fun bar() {}
}
}
Calling Kotlin class of companion object from Java:
A.foo();
A.Companion.foo();
A.Companion.bar();
© 2022 - 2024 — McMap. All rights reserved.