Kotlin List.lastOrNull() – Examples

Kotlin List.lastOrNull()

The Kotlin List.lastOrNull() function returns the last element, or null if the list is empty. You can also provide a predicate as argument to lastOrNull(), in which case, the function returns the last element matching the given predicate, or null if no such element was found.

Syntax

List.lastOrNull()

Returns the last element, or null if the list is empty.

List.lastOrNull(predicate)

Returns the last element matching the given predicate, or null if no such element was found.

Example 1: Getting the last element of a list

In this example, we have to get the last element of a given list of strings, using List.lastOrNull() function.

  1. Take a list of strings.
  2. Find the last item in the list using List.lastOrNull().
  3. Print the last item.

Program

fun main() {
    val list1 = listOf("apple", "google", "bing")
    val last = list1.lastOrNull()
    print(last)
}

Output

bing

Example 2: Getting the last element of an empty list

In this example, we get the last element of an empty list using lastOrNull() function. Since the list is empty, the function returns null.

Program

fun main() {
    val list1 = listOf<String>()
    val last = list1.lastOrNull()
    print(last)
}

Output

null

Example 3: Getting the last element of a list with predicate(condition)

In this example, we

  1. Take an empty list.
  2. Define a predicate, which returns True if the string starts with character 'e'.
  3. Find the last element that matches this predicate using List.lastOrNull() function.
  4. Print the value returned by the lastOrNull() function.

Program

fun main() {
    val list1 = listOf<String>("apple", "google", "bing")
    val predicate: (String) -> Boolean = {it.startsWith() == 'e'}
    val last = list1.lastOrNull(predicate)
    print(last)
}

Output

google

Example 4: Getting the last element of a list with predicate(condition)

In this example, we

  1. Take a list of strings such that no string starts with character 'f'.
  2. Define a predicate, which returns True if the string starts with character 'f'.
  3. Find the last element that matches this predicate using List.lastOrNull() function.
  4. Print the value returned by the lastOrNull() function.

Program

fun main() {
    val list1 = listOf<String>("apple", "google", "bing")
    val predicate: (String) -> Boolean = {it.startsWith() == 'e'}
    val last = list1.lastOrNull(predicate)
    print(last)
}

Output

google

Since, there is no element that satisfies the given predicate, lastOrNull() function returned null.