Kotlin Training Program

DOWNLOAD APP

FEEDBACK

all(), any() functions

To check a predicate / condition against all elements of a collection, we have all() & any() functions. The difference between the two is :

 // Syntax :
coll.all { /* Predicate */ }
coll.any { /* Predicate */ }
 

Example :

 fun main() {
		val nums = listOf(-1, 0, 1)
		println("all > 0 ? ${nums.all { it > 0 }}")
		println("at least one > 0 ? ${nums.any { it > 0 }}")
}

/* Output :
all > 0 ? false
at least one > 0 ? true */
 

Special case : When collection is empty, all() returns true & any() returns false.