🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The last function in Kotlin is used to return the last element of an array that matches a given predicate. If no predicate is provided, it returns the last element of the array. This function is part of the Kotlin standard library and provides a simple way to access elements from the end of an array.
Table of Contents
- Introduction
lastFunction Syntax- Understanding
last - Examples
- Basic Usage
- Using
lastwith a Condition - Handling Empty Arrays
- Using
lastwith Custom Types
- Real-World Use Case
- Conclusion
Introduction
The last function is used to return the last element of an array, either unconditionally or based on a given condition. If no such element is found when a condition is provided or if the array is empty when no condition is provided, it throws an exception.
last Function Syntax
The syntax for the last function is as follows:
fun <T> Array<out T>.last(): T
fun <T> Array<out T>.last(predicate: (T) -> Boolean): T
Parameters:
predicate: A lambda function that takes an element of typeTand returnstrueif the element matches the condition,falseotherwise (optional).
Returns:
- The last element of the array or the last element that matches the predicate.
Throws:
NoSuchElementExceptionif no element is found that matches the predicate, or if the array is empty when no predicate is provided.
Understanding last
The last function provides a convenient way to access elements from the end of an array. When used without a predicate, it returns the very last element. When used with a predicate, it returns the last element that matches the given condition.
Examples
Basic Usage
To demonstrate the basic usage of last, we will create an array of integers and return the last element.
Example
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val lastNumber = numbers.last()
println("Last element: $lastNumber")
}
Output:
Last element: 5
Using last with a Condition
This example shows how to use last to return the last element that matches a given condition.
Example
fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val lastEvenNumber = numbers.last { it % 2 == 0 }
println("Last even element: $lastEvenNumber")
}
Output:
Last even element: 4
Handling Empty Arrays
This example demonstrates how to handle cases where the array is empty.
Example
fun main() {
val emptyArray = emptyArray<Int>()
try {
val lastElement = emptyArray.last()
println("Last element: $lastElement")
} catch (e: NoSuchElementException) {
println("Error: ${e.message}")
}
}
Output:
Error: Array is empty.
Using last with Custom Types
This example shows how to use last with an array of custom objects.
Example
data class Person(val name: String, val age: Int)
fun main() {
val people = arrayOf(
Person("Ravi", 25),
Person("Anjali", 30),
Person("Priya", 22)
)
val lastPersonAbove25 = people.last { it.age > 25 }
println("Last person above 25: $lastPersonAbove25")
}
Output:
Last person above 25: Person(name='Anjali', age=30)
Real-World Use Case
Finding the Last Active User
In real-world applications, the last function can be used to find the last element that matches a specific condition, such as finding the last active user in a list.
Example
data class User(val name: String, val isActive: Boolean)
fun main() {
val users = arrayOf(
User("Ravi", false),
User("Anjali", true),
User("Priya", true)
)
val lastActiveUser = users.last { it.isActive }
println("Last active user: $lastActiveUser")
}
Output:
Last active user: User(name='Priya', isActive=true)
Conclusion
The last function in Kotlin is a convenient method for accessing the last element of an array, either unconditionally or based on a given predicate. It provides a simple way to retrieve elements from the end of an array and can be useful for filtering and finding elements based on specific conditions. By understanding and using this function, you can effectively manage element access operations in your Kotlin applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment