The onEach() extension function in Kotlin performs the given action on each element and returns the collection itself afterwards.
The syntax of Set.onEach() extension function is:
fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C
This onEach() extension function of Set performs the given action on each element and returns the collection itself afterwards.
Parameter | Optional/Required | Description |
---|---|---|
action | required | The action to be performed on each element. |
Set.onEach() returns value of type C
.
Using onEach() to print each element in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.onEach { println(it) }
println(numbers)
}
1 2 3 4 5 [1, 2, 3, 4, 5]
Using onEach() to convert each element to uppercase and print it.
For example,
fun main() {
val strings = setOf("one", "two", "three")
strings.onEach { println(it.uppercase()) }
println(strings)
}
ONE TWO THREE [one, two, three]
Using onEach() to print the name of each custom object in a set.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
people.onEach { println(it.name) }
println(people)
}
Alice Bob Charlie [Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about onEach() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.