Kotlin Array - find() Function



The Kotlin array find() function is used to return the first element matching the given predicate/condition or null if no such element is found.

In general, this function finding the element that satisfying the given predicate first.

Syntax

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

fun <T> Array<out T>.find( 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 a first element matching the predicate. Otherwise; null.

Example 1

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

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val elem = number.find{it>2}
   println("first element greater than 2: $elem")
}

Output

On execution of the above code we get the following result −

first element greater than 2: 3

Example 2

Now, let's see another example. Here, we use the find() 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.find{it%2==0}
   println("first element divisible by 2: $elem")
}

Output

After execution of the above code we get the following output −

first element divisible by 2: 2

Example 3

The example below creates an array that stores strings. We then use the find() 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 first_elem = strings.find{it.length>3}
   println("first string having length more than 3: $first_elem")
}

Output

The above code produce following output −

first string having length more than 3: Hello
kotlin_arrays.htm
Advertisements