any(), none() & all() : Kotlin
--
Kotlin is a powerful language that reduces a lot of boilerplate code required to perform basic operations in comparison to Java. The classic examples for the same are any, non
and all
functions which were added to the Iterable interface and Map interface.
This post was originally posted at https://agrawalsuneet.github.io/blogs/any-none-all-kotlin/ and reposted on Medium on 28th April 2021.
Let try to understand what do they do, why they are required and when to use them. But before we begin, I am assuming a basic knowledge of Map
, Set
and List
.
The List
provides the functionality to maintain the ordered collection. whereas Set
and Map
don’t provide the ordering. Both of them provides uniqueness but Map
is a key-value pair mapping.
In short, all three of them are used to store data/objects of similar types.
Since the collection is involved, filtering will be required to iterate the data faster.
To make this filter easier, Kotlin has added a few functions as an extension function to Iterable as well as Map.
Let look at them one by one.
Any
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.
val list = listOf("one", "two", "three", "four")
val set = setOf("one", "two", "three", "four")
val map = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four")
println(list.any { it.endsWith("e") }) // true
println(set.any { it.endsWith("e") }) // true
println(map.any { it.value.endsWith("e") }) // true