Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!