0
votes

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?

1

1 Answers

3
votes

Perhaps like this:

// CallExtensionFunction.java
package com.example.groundup;

public class CallExtensionFunction {

    public static void main(String[] args) {

        MyModel myModel = new MyModel();

        int bar = MyModelKt.bar(myModel);

        System.out.println(bar);
    }
}


// MyModell.kt
package com.example.groundup

fun MyModel.bar(): Int {
    return this.name.length
}

class MyModel() {
   val name = "Hugo"
}

The extension function is provided in the corresponding singleton with the suffix "Kt" as a static method.