Kotlin Set last()
Syntax & Examples


Set.last() extension function

The last() extension function in Kotlin returns the last element in the set. If a predicate is provided, it returns the last element that matches the given predicate.


Syntax of Set.last()

There are 2 variations for the syntax of Set.last() extension function. They are:

1.
fun <T> Set<T>.last(): T

This extension function returns the last element.

Returns value of type T.

2.
fun <T> Set<T>.last(predicate: (T) -> Boolean): T

Parameters

ParameterOptional/RequiredDescription
predicateoptionalA function that takes an element and returns true if the element matches the condition.

This extension function returns the last element matching the given predicate.

Returns value of type T.



✐ Examples

1 Getting the last element

Using last() to get the last element in a set.

For example,

  1. Create a set of integers.
  2. Use last() to get the last element in the set.
  3. Print the resulting element.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val lastNumber = numbers.last()
    println(lastNumber)
}

Output

5

2 Getting the last even number

Using last() to get the last even number in a set.

For example,

  1. Create a set of integers.
  2. Use last() with a predicate function that checks for even numbers.
  3. Print the resulting number.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8)
    val lastEven = numbers.last { it % 2 == 0 }
    println(lastEven)
}

Output

8

3 Getting the last string with length greater than 2

Using last() to get the last string with a length greater than 2 in a set.

For example,

  1. Create a set of strings.
  2. Use last() with a predicate function that checks for strings with a length greater than 2.
  3. Print the resulting string.

Kotlin Program

fun main() {
    val strings = setOf("a", "ab", "abc", "abcd")
    val lastLongString = strings.last { it.length > 2 }
    println(lastLongString)
}

Output

"abcd"

Summary

In this Kotlin tutorial, we learned about last() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.