我有點被Koltin lambda表達式困惑,我想知道如何使用它給出下面的代碼片段:科特林拉姆達與接口作爲參數
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);
}
}
我怎麼能在這種情況下,利用拉姆達在科特林?
[Android Studio中的可能的複製轉換Java來科特林錯誤無法推斷該參數的類型。請明確指定](https://stackoverflow.com/questions/44247827/android-studio-converting-java-to-kotlin-error-cannot-infer-a-type-for-this-para) – zsmb13