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?
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.
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.
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.
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.
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' }
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