How do I call a function written in a kotlin class , in java?

Marissa Nicholas :

I am using both Kotlin and java in my codebase. But I was wondering if there is a way I can reference a kotlin function from java? Here's my kotlin code : MyEvent.kt

open class MyEvent {
    @Inject
    lateinit var myService: MyService

    @Inject
    lateinit var app: MyApp

    var name: String = ""
    var options: MutableMap<String, String> = hashMapOf()
    var metrics: MutableMap<String, Double> = hashMapOf()

    init {
        app.component.inject(this)
    }

    fun identify() {
        myService.identify()
    }

}

Now, in my base application class call "MyApplication", I want to call identify function. (I . know in kotlin we can do this via MyEvent().identify ) but was wondering how do we go about it in java? Any clue?

Thanks in advance!

LppEdd :

It's the exact same thing in Java. Keep in mind they share the same underlying bytecode.

final MyEvent myEvent = new MyEvent();
myEvent.identify();

Look at the produced bytecode for the Kotlin MyEvent class (decompiled)

public class my/package/MyEvent {
  ...

  public final identify()V
   L0
    LINENUMBER 14 L0
    RETURN // Omitted myService.identify()
  ...

A companion object is translated to a static class property in Java.
For example, for this Kotlin code

open class MyEvent {
    companion object {
        fun test() = ""
    }
    ...
}

This is the resulting bytecode

static <clinit>()V
    NEW my/package/MyEvent$Companion
    DUP
    ACONST_NULL
    INVOKESPECIAL my/package/MyEvent$Companion.<init> (Lkotlin/jvm/internal/DefaultConstructorMarker;)V
    PUTSTATIC my/package/MyEvent.Companion : Lmy/package/MyEvent$Companion;
    RETURN
    MAXSTACK = 3
    MAXLOCALS = 0
}

Which means, basically

public class MyEvent {
   public static final Companion Companion = new Companion(...);
   ...
}

So, in Java you'd access it using

MyEvent.Companion.test();

For

open class MyEvent {
    object Factory {
        fun test() = ""
    }
    ...
}

It would be, in Java

MyEvent.Factory.INSTANCE.test();

Ultimately Java doesn't have the concept of companion objects.
Instead, static properties and methods are used.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78372&siteId=1