How to implement a java.util.function.Predicate as Kotlin lambda?
If in case want to declare as a property:
private val normal = Predicate<Int> { true }
private val even = Predicate<Int> { it % 2 == 0 }
private val odd = even.negate()
fun main() {
println("Normal count ${get(normal)}")
println("Even count ${get(even)}")
println("Odd count ${get(odd)}")
}
fun get(predicate: Predicate<Int>): Int {
val filter = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).filter { predicate.test(it)}
println(filter)
val map = filter.map { it * 2 }
println(map)
return map.sum()
}
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>)