Is it possible to access extension functions from Java code?
I defined the extension function in a Kotlin file.
package com.test.extensions
import com.test.model.MyModel
/**
*
*/
public fun MyModel.bar(): Int {
return this.name.length()
}
Where MyModel
is a (generated) java class.
Now, I wanted to access it in my normal java code:
MyModel model = new MyModel();
model.bar();
However, that doesn't work. The IDE won't recognize the bar()
method and compilation fails.
What does work is using with a static function from kotlin:
public fun bar(): Int {
return 2*2
}
by using import com.test.extensions.ExtensionsPackage
so my IDE seems to be configured correctly.
I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.
What am I doing wrong? Is this even possible?
You can always see the actual Java code which is getting generated from your Kotlin code by going to
Tools > Kotlin > Show Kotlin Bytecode
, then clickingDecompile
. This can help you tremendously. In your case the Java code will look like this if you haveMyModelExtensions.kt
you can improve over this by using
@JvmName
on the file containingbar
:and it will result in this code:
Using
MyModels
is in line with what Effective Java suggests for utility classes. You can also rename your method like this:then from the Java side it will look idiomatic:
You need to duplicate your functions in the class files:
Create Kotlin file , for ex Utils.kt
Enter the code
OR
In kotlin use:
In Java use this: