Kotlin List.take() – Examples

Kotlin List take()

The List take() function in Kotlin is used to create a new list containing the first n elements from the original list. It returns a new list with the specified number of elements.

Syntax

The take() function has the following syntax:

fun <T> List<T>.take(n: Int): List<T>

Parameters

ParameterDescription
nThe number of elements to take from the beginning of the list.

Return Value

The take() function returns a new list containing the first n elements from the original list. If the original list has fewer than n elements, it returns the entire original list.

Example 1: Taking Elements from a List

This example demonstrates how to use take() to create a new list with the first n elements from the original list.

In this example,

  1. Create a list of numbers, numbers.
  2. Use take() to create a new list containing the first 3 elements from the list.
  3. The take() function returns a new list with elements [1, 2, 3].

Kotlin Program

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    val firstThree = numbers.take(3)
    println("First three elements: $firstThree")
}

Output

Kotlin List.take() - Example 1

Example 2: Taking Elements from an Empty List

In this example, we use take() to create a new list from an empty list.

In this example,

  1. Create an empty list, emptyList.
  2. Use take() to create a new list containing the first 3 elements from emptyList.
  3. The take() function returns an empty list because the original list is empty.

Kotlin Program

fun main() {
    val emptyList = emptyList<Int>()
    val firstThree = emptyList.take(3)
    println("First three elements from empty list: $firstThree")
}

Output

Kotlin List.take() - Example 2

Summary

The take() function in Kotlin is useful for creating a new list containing the first n elements from the original list. It handles cases where the original list has fewer than n elements by returning the entire original list.