Server Side Kotlin-09

Server Side Kotlin-09

·

1 min read

partition() filters a collection by a predicate and makes Pair of Lists, the first list containing elements from collection that matches the predicate and the second one containing rest of the element.

val games = listOf("unity", "unreal", "godot", "bevy")
val (match, rest) = games.partition { it.length > 4 }
println(match)
println(rest)

output
[unity, unreal, godot]
[bevy]
any() and none() can be used without a predicate: in this case they just check the collection emptiness.

val games = listOf("unity", "unreal", "godot", "bevy")
val empty = emptyList<String>()

println(games.any())
println(empty.any())

println(games.none())
println(empty.none())

output

true
false
false
true

any() returns true if at least one element matches the given predicate.

none() returns true if none of the elements match the given predicate.

all() returns true if all elements match the given predicate. Also all() returns true when called with any valid predicate on an empty collection. It is known as vacuous truth.

val games = listOf("unity", "unreal", "godot", "bevy")

println(games.any { it.endsWith("y") })
println(games.none { it.endsWith("a") })
println(games.all { it.endsWith("e") })
// vacuous truth
println(emptyList<Int>().all { it > 4})

output

true
true
false
true