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 list containing the integers 1, 2, 3, 4, 5.
  • We call the take function on list with parameter 3, which returns the first 3 elements of the list.
  • The result, which is a list containing 1, 2, 3, is stored in result.
  • Finally, we print the value of result to standard output using the println function.

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 list containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We call the take function on list with parameter 2, which returns the first 2 elements of the list.
  • The result, which is a list containing 'a', 'p', is stored in result.
  • Finally, we print the value of result to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val result = list.take(2);
    println(result);
}

Output

[a, p]

3 Example

In this example,

  • We create a list named list containing the strings "apple", "banana", "cherry", "date", "elderberry".
  • We call the take function on list with parameter 4, which returns the first 4 elements of the list.
  • The result, which is a list containing "apple", "banana", "cherry", "date", is stored in result.
  • Finally, we print the value of result to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;, &quot;elderberry&quot;);
    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.