Kotlin Array - takeLast() Function



The Kotlin array takeLast() function is used to return a list containing last n element of an array. n is the number of elements that should be returned from last of an array.

Exception

This function throw an exception IllegalArgumentException if n is negative.

Syntax

Following is the syntax of Kotlin array takeLast() function −

fun <T> Array<out T>.takeLast(n: Int): List<T>

Parameters

This function accepts a parameter n, which represents a number that must be smaller or equal to the size of an array.

Return value

This function returns a list containing last n elements.

Example 1

Following is a basic example to demonstrate the use of takeLast() function −

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array elements: ")
   println(arr.joinToString())

   // use takeLast function
   val list = arr.takeLast(3)
   println("list: "+ list)
}

Output

The above code generate following output −

Array elements: 3, 4, 5, 6
list: [4, 5, 6]

Example 2

Let's see another example. Here, we use the takeLast function to return a list containing last n element of an string array −

fun main(args: Array<String>){
   var arr = arrayOf<String>("Daisy", "Lily", "Rose", "Lotus", "Sunflower")
   print("Array elements: ")
   println(arr.joinToString())

   // use takeLast function
   val list = arr.takeLast(2)
   println("List of flower: "+ list)
}

Output

Following is the output −

Array elements: Daisy, Lily, Rose, Lotus, Sunflower
List of flower: [Lotus, Sunflower]

Example 3

Let's see below example where we have an array of Product objects, and we want to display last two product details using takeLast() function −

data class Product(val name: String, val price: Double)

fun main(args: Array<String>) {
   val products = arrayOf(
      Product("Laptop", 999.99),
      Product("Mouse", 19.99),
      Product("Keyboard", 49.99),
      Product("Monitor", 199.99)
   )
   // use takeLast function
   val price = products.takeLast(2)

   // Display the result
   println("Product and Price List: $price")
}

Output

The above code produce following output −

Product and Price List: [Product(name=Keyboard, price=49.99), Product(name=Monitor, price=199.99)]
kotlin_arrays.htm
Advertisements