Kotlin List take()
Syntax & Examples
Syntax of List.take()
The syntax of List.take() extension function is:
fun <T> Iterable<T>.take(n: Int): List<T>This take() extension function of List returns a list containing first n elements.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining the integers1, 2, 3, 4, 5. - We call the
takefunction onlistwith parameter3, which returns the first 3 elements of the list. - The result, which is a list containing
1, 2, 3, is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = list.take(3);
println(result);
}Output
[1, 2, 3]
2 Example
In this example,
- We create a list named
listcontaining the characters'a', 'p', 'p', 'l', 'e'. - We call the
takefunction onlistwith parameter2, which returns the first 2 elements of the list. - The result, which is a list containing
'a', 'p', is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "p", "p", "l", "e");
val result = list.take(2);
println(result);
}Output
[a, p]
3 Example
In this example,
- We create a list named
listcontaining the strings"apple", "banana", "cherry", "date", "elderberry". - We call the
takefunction onlistwith parameter4, which returns the first 4 elements of the list. - The result, which is a list containing
"apple", "banana", "cherry", "date", is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list.take(4);
println(result);
}Output
[apple, banana, cherry, date]
Summary
In this Kotlin tutorial, we learned about take() extension function of List: the syntax and few working examples with output and detailed explanation for each example.