Accessing Kotlin extension functions from Java

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?

10 Answers
10

Leave a Comment