gpt4 book ai didi

java - Kotlin调用提供的Unit类型的参数

转载 作者:行者123 更新时间:2023-12-02 12:39:04 24 4
gpt4 key购买 nike

我现在和Kotlin有点挣扎。

在Java中,我要做的是:

public void doSomething(Consumer<String> onResult) {
...
onResult.accept("Hello");
}

现在,据我所知,在 Kotlin ,我会像这样:
fun doSomething(onResult: (message: String) -> Unit) {
...
}

现在如何将值传递给onResult?
fun doSomething(onResult: (message: String) -> Unit) {
onResult.apply { "Hello" }
}

或如何去做?

最佳答案

使用常规方法调用。在doSomething方法中,您的参数是一个函数。因此,您可以使用onResult("Hello");将值传递给传入函数

fun mainMethod(m: String, functionAsParam: (m: String) -> Unit) {
functionAsParam(m)
}

// my function to pass into the other
fun functionAsParam(m: String) {
println("my message: $m")
}

只是一个想法;
//Also you can call like this method 
fun tryMySolution() {
mainMethod("hi", ::functionAsParam)
}

关于java - Kotlin调用提供的Unit类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52327167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com