简体   繁体   中英

Kotlin: get a Reference to a Function of a Class' instance

I am trying to pass a function to a function in Kotlin here is my code.

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

The function I'm passing is from Regex class "containsMatchIn"

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

I know about the :: function reference operator but I don't know how to use it in this situation

In Kotlin 1.0.4, bound callable references (those with expressions on left-hand side) are not available yet, you can only use class name to the left of :: .

This feature is planned for Kotlin 1.1 and will have the following syntax:

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

Until then, you can express the same using lambda syntax. To do it, you should capture a Regex into a single-argument lambda function:

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

One-line equivalent using with(...) { ... } :

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

Here, with binds the Regex to receiver for the outer braces and returns the last and the only expression in the outer braces -- that is, the lambda function defined by the inner braces. See also: the idiomatic usage of with .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM