Kotlin:获取对类实例的函数的引用

Abd*_*lat 3 function kotlin

我试图将函数传递给Kotlin中的函数,这是我的代码.

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

我传递的函数来自Regex类"containsMatchIn"

val f = Regex.fromLiteral("some regex").containsMatchIn
Run Code Online (Sandbox Code Playgroud)

我知道:: function引用操作符,但我不知道在这种情况下如何使用它

hot*_*key 5

在Kotlin 1.0.4中,绑定的可调用引用(左侧有表达式的引用)尚不可用,您只能使用左侧的类名::.

此功能计划用于Kotlin 1.1,并具有以下语法:

val f = Regex.fromLiteral("some regex")::containsMatchIn
Run Code Online (Sandbox Code Playgroud)

在此之前,您可以使用lambda语法表达相同的内容.要做到这一点,你应该捕获Regex一个单参数lambda函数:

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

单线等效使用with(...) { ... }:

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

在这里,with绑定Regex到外部大括号的接收器,并返回外大括号中的最后一个和唯一的表达式 - 即由内括号定义的lambda函数.另见:惯用法with.

  • 值得注意的是,`regex.containsMatchIn(s)`也可以表示为s中的`regex` (3认同)