Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a java.util.function.Predicate as Kotlin lambda?

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

like image 380
Chriss Avatar asked Feb 16 '18 14:02

Chriss


People also ask

How does lambda function work in Kotlin?

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.

How do you pass lambda as parameter Kotlin?

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.

What is predicate in lambda expression?

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.


1 Answers

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>)
like image 176
Chriss Avatar answered Oct 18 '22 15:10

Chriss