我对Koltin lambdas有点困惑,我想知道如何使用它给出以下代码片段:
interface KotlinInterface {
fun doStuff(str: String): String
}
并且需要将此接口作为参数传递的函数:
fun kotlinInterfaceAsArgument(kotlinInterface: KotlinInterface): String{
return kotlinInterface.doStuff("This was passed to Kotlin Interface method")
}
fun main(args: Array<String>){
val newString = kotlinInterfaceAsArgument({
str -> str + " | It's here" //error here (type mismatch)
})
}
但是,相同的逻辑但在Java中编译并按预期运行 .
public class JavaClass {
public String javaInterfaceAsArgument(JavaInterface javaInterface){
String passedToInterfaceMethod = "This was passed to Java Interface method";
return javaInterface.doStuff(passedToInterfaceMethod);
}
public interface JavaInterface {
public String doStuff(String str);
}
}
和
public class Main {
public static void main(String[] args) {
JavaClass javaClass = new JavaClass();
String newValue = javaClass.javaInterfaceAsArgument(str -> str + " | It's here!");
System.out.println(newValue);
}
}
在这种情况下,如何在Kotlin中使用lambda?
2 回答
SAM conversion(从1.1开始)仅适用于Java接口,而不适用于Kotlin接口 .
您可以通过某些方法修复代码in this answer .
Edit: 我意识到这与另一个问题完全相同,因为即使错误也是一样的 .
纯Kotlin的正确方法是使用高阶函数:https://kotlinlang.org/docs/reference/lambdas.html
使用高阶函数,您可以将函数作为参数传递给它 .
如果我们谈谈你的例子: