Kotlin Array - last() Function



The Kotlin array last() function retrieves the element at the last index of the array. If the array is empty, this function returns a NoSuchElementException error.

Another overloaded version of the function accepts a predicate and returns the last element in the array that gives true for the boolean predicate expression.

Syntax

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

fun <T> Array<out T>.last(): T
or,
inline fun <T> Array<out T>.last(
   predicate: (T) -> Boolean
): T

Parameters

This function does not accepts any parameters

Return value

This function returns a value of any data type, which depends on the type of the last element of the array.

Example 1

The following is a basic example, creates an array of size 5 and using the last() function to get the last element.

fun main(args: Array<String>) {
   var array = Array(5) { i -> i }
   try {
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
	  println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value of the last element of the array is: 4

Example 2

Now, let's see another example, here we creates an array that stores different type of data. We then use the last() function to get the value of the last index −

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the last() function
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value of the last element of the array is: tutorialspoint.com

Example 3

The below example creates an empty array and uses the last() function to display the value of the last index −

fun main(args: Array<String>) {
   var array = emptyArray<String>()
   try {
      val value = array.last()
      println("The value of the last element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

Output

The above code generate the following output. If an exception occurs −

An element passing the given predicate does not exist or the array is empty
kotlin_arrays.htm
Advertisements