Kotlin Array - first() Function



The Kotlin array first() function is used to return the first element of an array that matches the given predicate or condition.

This function takes a parameter (predicate) that does not need to be passed every time. You can choose whether to provide a condition. For example, in the ArrayOf(2,4,5,6).first() function returns the first element of an array (i.e. 2).

Exceptions

This function throws single exception −

  • NoSuchElementException: If no such element is found in an array then this function throws this exception.

Syntax

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

fun <T> Array<out T>.first(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 of an array. Otherwise; an exception if no such element is found.

Example 1

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

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5)
   val first_elem = number.first()
   println("first element if an array: $first_elem")
}

Output

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

first element if an array: 1

Example 2

Now, let's see another example. Here, we use the first() function to return first element matching the given predicate −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val elem = number.first{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 gives an exception if element does not satisfy the predicate −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val elem = strings.first{it.length<1}
   println("first element 5: $elem")
}

Output

The above code produce following output −

Exception in thread "main" java.util.NoSuchElementException: Array contains no element matching the predicate.
kotlin_arrays.htm
Advertisements