Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

I'm trying to find whether a character belongs to a string.

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

But I can't understand that syntax. From docs:

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

How can I pass a predicate to the function?

like image 873
barbara Avatar asked Nov 10 '14 16:11

barbara


People also ask

What is () -> unit in Kotlin?

Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.

What is any () in Kotlin?

Any is a function that is added as an extension to Iterable and Map interfaces, which take a higher-order function as param to predicate the condition and return Boolean as true, if any of the items in List , Set or Map confirms that condition, else return false.

How do you pass a list to a function in Kotlin?

Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas. listOf(1, 2, 3, 4, 5, 6) returns a read-only list of integers from 1 through 6.

Is there an any type in Kotlin?

In Kotlin the Any type represents the super type of all non-nullable types. It differs to Java's Object in 2 main things: In Java, primitives types aren't type of the hierarchy and you need to box them implicitly, while in Kotlin Any is a super type of all types.


1 Answers

Full syntax:

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

We can make some simplifications.

First, since lambda parameter comes last, we can place it outside of the parentheses and omit them entirely, when there is no more parameters left.

Second, for lambda function literal with one parameter it is possible to omit the parameter declaration and reference that parameter by it name.

Thus the simplified equivalent would be:

s.any { it == 'd' }
like image 67
bashor Avatar answered Oct 11 '22 04:10

bashor