Kotlin List takeLast()
Syntax & Examples
Syntax of List.takeLast()
The syntax of List.takeLast() extension function is:
fun <T> List<T>.takeLast(n: Int): List<T>This takeLast() extension function of List returns a list containing last n elements.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1with elements1, 2, 3, 4, 5. - We use the
takeLastfunction with an argument3onlist1to get the last 3 elements. - The result is a new list containing the last 3 elements of
list1. - We print the result using
println().
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.takeLast(3)
println(result)
}Output
[3, 4, 5]
2 Example
In this example,
- We create a list of characters named
list1with elements'a', 'b', 'c', 'd', 'e'. - We use the
takeLastfunction with an argument2onlist1to get the last 2 elements. - The result is a new list containing the last 2 elements of
list1. - We print the result using
println().
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf('a', 'b', 'c', 'd', 'e')
val result = list1.takeLast(2)
println(result)
}Output
[d, e]
3 Example
In this example,
- We create a list of strings named
list1with elements"apple", "banana", "cherry", "date", "elderberry". - We use the
takeLastfunction with an argument4onlist1to get the last 4 elements. - The result is a new list containing the last 4 elements of
list1. - We print the result using
println().
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry", "date", "elderberry")
val result = list1.takeLast(4)
println(result)
}Output
[banana, cherry, date, elderberry]
Summary
In this Kotlin tutorial, we learned about takeLast() extension function of List: the syntax and few working examples with output and detailed explanation for each example.