How to access Kotlin companion object in Java?

I convert one of my Java class to Kotlin and the class as below.

class MainApplication : Application() {
    companion object {
        operator fun get(context: Context): MainApplication {
            return context.applicationContext as MainApplication
        }
    }
}

It has a static function get.

I still have a Java function accessing it.

MainApplication application = MainApplication.get(mContext);

It was good when MainApplication is in Java. But not when MainApplication in Kotlin, the above code error

Error:(27, 54) error: cannot find symbol method get(Context)

How could I access get in my Java code above?

Answers


You can add @JvmStatic annotation to the method in companion object to make Kotlin generate a static method.

class MainApplication : Application() {
    companion object {
        @JvmStatic fun get(context: Context): MainApplication {
            return context.applicationContext as MainApplication
        }
    }
}

you can then access it from Java like before converting to Kotlin:

MainApplication application = MainApplication.get(mContext);

EDIT: I feel obliged to add something I learned recently: @JvmStatic doesn't actually move where the method gets generated. It duplicates it, by generating a static method for Java in addition to the method on the companion object. Personally I think this isn't great and it can have some implications depending on a use case, so something worth knowing.


Ops, I got it. Just use the below.

MainApplication application = MainApplication.Companion.get(mContext);

By omitting the name of your companion object, the name Companion must be used to access the methods.

Example:

class MyClass1 {
    companion object Object1 {
        fun method1 {
        }
    }
}

class MyClass2 {
    companion object {
        fun method2 {
        }
    }
}

To invoke the first companion object method you would do the following:

MyClass1.method1()

To invoke the second:

MyClass2.Companion.method2()

See the Kotlin docs on Companion Objects for details.


Need Your Help

Change the selected value of a drop-down list with jQuery

javascript jquery html-select

I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery. Using regular JavaScript, I would do something lik...

Where is the textmode video buffer if it isn't at 0xB8000?

graphics dos vga

About 15 years ago, I used to amuse myself and annoy my CS teacher by writing bad code that would directly modify the text on the monitor. This was/is easily done by accessing video memory at 0xB8...