Search code examples
javaandroidkotlincallback

How to pass callback function from Java to Kotlin class


I have a Kotlin class as follows (this is a sample for ease, hence it doesn't 'do' anything useful)

class MyKotlinClass (private val handleSomeCallBack: (ByteArray) -> Unit) {
    private val someBuffer = BytesBuilder()

    fun myFunction(bytesList: List<Byte>) {
        handleSomeCallBack(someBuffer.toArray())
    }
}

I want to call this code from a java class, hence, in that class I have the following declared:

public MyJavaClass() {
    messageParser = new MyClass(handleSomeCallback);
}

The callback method being passed is:

private void handleSomeCallback(byte[] dataBytes) {

}

(MyClass is correctly declared within the file)

The issue I'm having is that I can't figure out how to pass the callback to the constructor of MyKotlinClass.

I have tried a variety of things including

messageParser = new MyClass(handleSomeCallback(byte[] dataBytes));

messageParser = new MyClass(this::handleSomeCallback(byte[] dataBytes));

But no matter what I try I receive an error.

I believe the answer is to do with lambdas but I can't quite see what the syntax should be for calling this from Java.


Solution

  • You can go with something like this:

    MyKotlinClass instance = new MyKotlinClass(byteArray -> {
        // your code
        return Unit.INSTANCE;
    });
    
    

    Or use Unit as return type of your separate method like suggested by @ADM here

    You just need to add

    compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
    }
    

    to your android block in app build.gradle