2016-09-25 74 views
3

我想將函數傳遞給Kotlin中的函數,這裏是我的代碼。Kotlin:獲取一個類的函數的參考'實例

fun validateValueWithFunc(value: String, parsefun: (CharSequence) -> Boolean, type: String){ 
    if(parsefun(value)) 
     print("Valid ${type}") 
    else 
     print("Invalid ${type}") 
} 

我傳遞的功能是從正則表達式類「containsMatchIn」

val f = Regex.fromLiteral("some regex").containsMatchIn 

我瞭解::函數引用運營商,但我不知道如何在這種情況下

使用

回答

5

在Kotlin 1.0.4中,bound callable references(表達式在左側)尚未提供,您只能使用use class name to the left of ::

此功能planned for Kotlin 1.1,將有以下語法:

val f = Regex.fromLiteral("some regex")::containsMatchIn 

在那之前,你可以表達同樣的使用lambda語法。要做到這一點,你應該捕捉Regex成單參數的lambda函數:

val regex = Regex.fromLiteral("some regex") 
val f = { s: CharSequence -> regex.containsMatchIn(s) } // (CharSequence) -> Boolean 

單行相當於使用with(...) { ... }

val f = with(Regex.fromLiteral("some regex")) { { s: CharSequence -> containsMatchIn(s) } } 

這裏,with結合的Regexreceiver的外大括號並返回最後一個和唯一的外括號中的表達式 - 也就是由內括號定義的lambda函數。另見:the idiomatic usage of with

+0

也許會更清楚地說明您正在使用lamda「捕獲」函數來捕獲實例,直到綁定的可調用引用可用。你的語法的第一個版本對初學者來說很難說服。 –

+0

@JaysonMinard,更新了答案。 – hotkey

+3

值得注意的是,'regex.containsMatchIn(s)'也可以表示爲's中的正則表達式' – Ilya