2017-06-03 71 views
1

我有點被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); 
    } 
} 

我怎麼能在這種情況下,利用拉姆達在科特林?

+3

[Android Studio中的可能的複製轉換Java來科特林錯誤無法推斷該參數的類型。請明確指定](https://stackoverflow.com/questions/44247827/android-studio-converting-java-to-kotlin-error-cannot-infer-a-type-for-this-para) – zsmb13

回答

2

SAM conversion(截至1.1)只適用於Java接口,不適用於Kotlin。

另請注意,此功能僅適用於Java interop;由於Kotlin具有適當的函數類型,所以函數自動轉換爲Kotlin接口的實現是不必要的,因此不受支持。

你可以通過一些方法來修復你的代碼in this answer

編輯:我意識到這是另一個問題的確切副本,因爲即使錯誤是相同的。

+0

因此,''有趣的main(參數:Array ){ \t println(JavaClass()。javaInterfaceAsArgument {it - > it +「| It's here」}) }'是正確答案嗎? – harshavmb

+0

那麼,在Java中定義接口是其中的一個選項。 – zsmb13

+0

很感謝。上面這個爲我工作,而不需要在kotlin中創建一個接口和函數。 – harshavmb

1

純科特林正確的方法是使用高階函數:https://kotlinlang.org/docs/reference/lambdas.html

隨着高階函數可以傳遞函數作爲它的參數。

如果我們談論你的例子:

fun kotlinFunctionAsArgument(kotlinFunction: (String) -> String): String { 
    return kotlinFunction("This was passed to Kotlin Function method") 
} 

fun main(args: Array<String>){ 
    val newString = kotlinFunctionAsArgument({ 
     str -> str + " | It's here" //there are no errors 
    }) 
}