
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - findLast() Function
The Kotlin array findLast() function is used to return the last element matching the given predicate/condition or null if no such element is found.
In general, this function finds the first element from the last that satisfying the given predicate first from last.
Syntax
Following is the syntax of Kotlin array findLast() function −
fun <T> Array<out T>.findLast( predicate: (T) -> Boolean ): T?
Parameters
This function accepts a predicate as a parameter. Predicate represent a condition which gives boolean value.
Return value
This function returns an element from the last matching the predicate. Otherwise; null.
Example 1
Following is the basic example to demonstrate the use of findLast() function −
fun main(args: Array<String>) { val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8) val elem = number.findLast{it>2} println("first element from last which is greater than 2: $elem") }
Output
On execution of the above code we get the following result −
first element from last which is greater than 2: 8
Example 2
Now, let's see another example. Here, we use the findLast() function to return a first element which is divisible by 2 −
fun main(args: Array<String>) { val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8) val elem = number.findLast{it%2==0} println("first element from last which is divisible by 2: $elem") }
Output
After execution of the above code we get the following output −
first element from last which is divisible by 2: 8
Example 3
The example below creates an array that stores strings. We then use the findLast() function to return the first string which length is greater than 3 −
fun main(args: Array<String>) { val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint") val elem = strings.findLast{it.length>5} println("first string from last having length more than 5: $elem") }
Output
The above code produce following output −
first string from last having length more than 5: tutorialspoint