Kotlin: How to pass a predicate to CharSequence.any ()?

I am trying to find if a character belongs to a string.

var s = "abcdef" var result = s.any('d') 

But I can not understand this syntax. From docs :

 fun CharSequence.any(predicate: (Char) -> Boolean): Boolean 

How to pass a predicate to a function?

+5
source share
1 answer

Full syntax:

 s.any({ ch -> ch == 'd' }) 

We can make some simplifications.

First, since the last parameter is lambda, we can place it outside the parentheses and completely omit them when more parameters are left.

Secondly, for a lambda function literal with one parameter, you can omit the parameter declaration and specify this parameter using it name.

Thus, the simplified equivalent would be:

 s.any { it == 'd' } 
+14
source

Source: https://habr.com/ru/post/1206573/


All Articles