3

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

maybe make it clearer that you are "wrapping" the function with a lamda to capture the instance, until bound callable references are available. The first verison of your syntax would be hard to beginners to grok.
It's worth noting that regex.containsMatchIn(s) can also be expressed as regex in s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.