英文:
How to pass callback function from Java to Kotlin class
问题
以下是您要求的翻译内容:
我有一个 Kotlin 类,如下所示(这只是一个示例,为了方便起见,因此它并没有执行任何有用的操作)
class MyKotlinClass(private val handleSomeCallBack: (ByteArray) -> Unit) {
private val someBuffer = BytesBuilder()
fun myFunction(bytesList: List<Byte>) {
handleSomeCallBack(someBuffer.toArray())
}
}
我想从 Java 类中调用此代码,因此在那个类中,我声明了以下内容:
public MyJavaClass() {
messageParser = new MyKotlinClass(this::handleSomeCallback);
}
传递的回调方法是:
private void handleSomeCallback(byte[] dataBytes) {
}
(MyKotlinClass 在文件中被正确声明)
我遇到的问题是,我无法弄清楚如何将回调传递给 MyKotlinClass 的构造函数。
我尝试了各种方法,包括:
messageParser = new MyKotlinClass(handleSomeCallback(dataBytes));
messageParser = new MyKotlinClass(this::handleSomeCallback(dataBytes));
但无论我尝试什么,都会收到错误。
我认为答案与 lambda 表达式有关,但我无法完全理解从 Java 中调用这个的语法应该是什么。
英文:
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.
答案1
得分: 1
你可以选择类似这样的方式:
MyKotlinClass instance = new MyKotlinClass(byteArray -> {
// 你的代码
return Unit.INSTANCE;
});
或者像@ADM在这里建议的那样,将Unit
用作你单独方法的返回类型:
只需在你的应用程序build.gradle
文件的android
块中添加以下内容:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论