Kotlin String - last() Function



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

The last() function retrieves the last character of the string. Similar to first(), it throws a NoSuchElementException for the string is empty or does not contain the specified character.

Syntax

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

fun last(
   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 last character, otherwise, returns the last character matching the given predicate.

Example 1: Get the Last Char

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

fun main() {
  val str = "tutorialspoint"
  val last_char = str.last();
  println("Last character of string: ${last_char}")
}

Output

Following is the output −

Last character of string: t

Example 2: Use last() with a Predicate

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

fun main() {
   val str = "tutorialsPoinT"
   val LastUppercase = str.last { it.isUpperCase() }
   println(LastUppercase)
}

Output

Following is the output −

T

Example 3: If no Char Matches the Predicate

Here, in this example, the last() function throws an exception if no character matches with a given predicate −

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

Output

You will get the following exception if no character matches the predicate −

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