Kotlin String - first() Function



The Kotlin string first() function is an extension function. It is designed to retrieve the first character of a string. It simplifies the process of accessing string boundaries, making our code cleaner and more natural.

The first() function returns the first character of the string. If the string is empty or does not contain the specified character, it throws a NoSuchElementException.

Syntax

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

fun first(
   predicate: (Char) -> Boolean
): Char

Parameters

This function accepts an optional parameter predicate, which represents the condition checked for each character.

Return value

If we do not pass the predicate then this function returns the first character, otherwise, returns the first character matching the given predicate.

Example 1: Display First Char of String

Following is the basic example, here how we can use first() function with string in Kotlin −

fun main() {
   val str = "tutorialspoint"
   val first_char = str.first();
   println("First character of string: ${first_char}")
}

Output

Following is the output −

First character of string: t

Example 2: Use Predicate to Display First Char

Now, let's look at another example of the first() function, how it returns the first character according to the given predicate.

fun main() {
   val str = "tutorialsPoint"
   val firstUppercase = str.first { it.isUpperCase() }
   println(firstUppercase)
}

Output

Following is the output −

P

Example 3: Throw an Exception

If no character matches with a given predicate, then the first()function throws the following exception.

fun main() {
   val str = "rythm"
   val firstVowel = str.first { it in "aeiouAEIOU" }
   println(firstVowel)
}

Output

Following is the output −

Exception in thread "main" java.util.NoSuchElementException: Char sequence contains no character matching the predicate.
kotlin_strings.htm
Advertisements