简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM