Kotlin Array.findLast()

Kotlin Array.findLast() function

In Kotlin, the Array.findLast() function is used to find the last element in the array that satisfies the given predicate. It returns the last element that matches the predicate or null if no such element is found.

In this tutorial, we’ll explore the syntax of the findLast() function and provide examples of its usage in Kotlin arrays, both with and without a predicate.

Syntax

The syntax of the findLast() function is as follows:

fun <T> Array<out T>.findLast(predicate: (T) -> Boolean): T?

where

ParameterDescription
predicateA lambda function that takes the element of the array as an argument and returns true or false.
Parameter of Array findLast() function

If no element satisfies the predicate or if the array is empty, the function returns null.

Examples for Array.findLast() function

1. Finding the Last Even Number

In this example, we’ll use findLast() to find the last even number from the given array of integers numbersArray.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 8, 9, 10, 11)

    // Finding the last even number
    val lastEvenNumber = numbersArray.findLast { it % 2 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
    println("Last Even Number\n$lastEvenNumber")
}

Output

Numbers Array
1, 3, 5, 7, 8, 9, 10, 11

Last Even Number
10

2. Finding the Last Element where No Element satisfies given Predicate

In this example, we’ll use findLast() function on an array of numbers, with a predicate to find the last even number. But, we have taken elements in the array such that there is no element that satisfies the given predicate.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 3, 5, 7, 9, 11)

    // Finding the last even number
    val lastEvenNumber = numbersArray.findLast { it % 2 == 0 }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
    println("Last Even Number\n$lastEvenNumber")
}

Output

Numbers Array
1, 3, 5, 7, 9, 11

Last Even Number
null

Summary

In this tutorial, we’ve covered the Array.findLast() function in Kotlin, its syntax, and how to use it to find the last element based on a predicate.