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:
fun <T> Set<T>.last(): T
This extension function returns the last element.
Returns value of type T
.
fun <T> Set<T>.last(predicate: (T) -> Boolean): T
Parameters
Parameter | Optional/Required | Description |
---|---|---|
predicate | optional | A 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,
- Create a set of integers.
- Use last() to get the last element in the set.
- 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,
- Create a set of integers.
- Use last() with a predicate function that checks for even numbers.
- 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,
- Create a set of strings.
- Use last() with a predicate function that checks for strings with a length greater than 2.
- 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.