How can I refer to companion objects from Java?

I have a mixed project, classes Java

and Kotlin

, and I want to know how I can reference companion objects

from my classes Java

.

+3


source to share


3 answers


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.

+4


source


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

      

+1


source


This is a Kotlin class with a companion object.

class A {
    companion object {
        @JvmStatic fun foo() {}
        fun bar() {}
    }
}

      

Calling Kotlin companion class from Java:

A.foo();
A.Companion.foo();
A.Companion.bar();

      

0


source







All Articles