The take() extension function in Kotlin returns a list containing the first n elements.
The syntax of Set.take() extension function is:
fun <T> Set<T>.take(n: Int): List<T>
This take() extension function of Set returns a list containing first n elements.
Parameter | Optional/Required | Description |
---|---|---|
n | required | The number of elements to take from the beginning. |
Set.take() returns value of type List
.
Using take() to get the first 3 elements of a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val firstThree = numbers.take(3)
println(firstThree)
}
[1, 2, 3]
Using take() to get the first 2 elements of a set of strings.
For example,
fun main() {
val strings = setOf("one", "two", "three", "four")
val firstTwo = strings.take(2)
println(firstTwo)
}
[one, two]
Using take() to get the first element of a set of custom objects.
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))
val firstPerson = people.take(1)
println(firstPerson)
}
[Person(name=Alice, age=30)]
In this Kotlin tutorial, we learned about take() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.