Kotlin Array - lastOrNull() Function



The Kotlin array lastOrNull() function is used to return the last element of an array or collection if the element is available, otherwise, it will return null if the array is empty.

This function can take the predicate as a parameter to retrieve the last element of an array if the condition is met. If no element satisfies the supplied predicate, null is returned.

Syntax

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

fun <T> Array<out T>.lastOrNull(): T?

Parameters

This function accepts a predicate as a parameter, which is an optional parameter.

Return value

This function returns an element. Otherwise; null.

Example 1

The following is a basic example to demonstrate the use lastOrNull() function −

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4)
   val lastelem = array.lastOrNull();
   println("The last element is: $lastelem");
}

Output

Following is the output −

The last element is: 4

Example 2

Now, let's create another example. Here, we create an empty array. We then use the lastOrNull function to check whether the array is empty −

fun main(args: Array<String>) {
   var array = arrayOf<Int>()
   val lastelem = array.lastOrNull();
   println("The last element is: $lastelem");
}

Output

Following is the output −

The last element is: null

Example 3

The below example uses the lastOrNull function with a predicate. If the predicate is matched by an element in the array, then the last element will be returned −

fun main(args: Array<String>) {
   var array = arrayOf<String>("Hello", "tutorialspoint", "India", "Pvt", "ltd")
   val lastelem = array.lastOrNull({it.length>4});
   println("The last element having length 5 is: $lastelem");
}

Output

Following is the output −

The last element having length 5 is: India
kotlin_arrays.htm
Advertisements