我正在尝试将函数传递给 Kotlin 中的函数,这是我的代码。
fun validateValueWithFunc(value: String, parsefun: (CharSequence) -> Boolean, type: String){
if(parsefun(value))
print("Valid ${type}")
else
print("Invalid ${type}")
}
我传递的函数来自 Regex 类“containsMatchIn”
val f = Regex.fromLiteral("some regex").containsMatchIn
我知道::函数引用运算符,但我不知道在这种情况下如何使用它
最佳答案
在 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
将 Regex
绑定(bind)到 receiver对于外括号并返回外括号中的最后一个也是唯一的表达式——即由内括号定义的 lambda 函数。另请参阅:the idiomatic usage of with
.
关于function - Kotlin:获取对类实例函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39686529/