I need to pass a java.util.function.Predicate
to a Java function. How can I implement it as Lambda in Kotlin?
The Java-Function I need to call:
public void foo(Predicate<String> p)
Java Lambda implemenation ✔ :
foo(text-> true)
Kotlin Lambda implemenation ❌:
foo{text:String -> true}
^^^^^^^^^^^^
Type mismatch.
Required: Predicate<String>
Found: (String) → Boolean
Kotlin-Version 1.2.21
Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
Predicate<T> is a generic functional interface that represents a single argument function that returns a boolean value (true or false). This interface available in java. util. function package and contains a test(T t) method that evaluates the predicate of a given argument.
Since Kotlin 1.4
foo({text -> true })
or
foo {text -> true}
Before Kotlin 1.4
These variants work:
foo(Predicate {text -> true })
foo(Predicate {true})
foo({true }as Predicate<String>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With