🎓 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
Introduction
In Kotlin, the Triple class is used to store three related values. It is a simple data structure that holds a triple of values, which can be of different types. The Triple class is useful when you need to return three values from a function or when you want to group three related values together.
Table of Contents
- What is the
TripleClass? - Creating a
Triple - Accessing Triple Values
- Triple Functions
- Examples of
Triple - Real-World Use Case
- Conclusion
1. What is the Triple Class?
The Triple class in Kotlin is a generic class that holds three values, often referred to as first, second, and third. It is defined as:
data class Triple<out A, out B, out C>(val first: A, val second: B, val third: C)
2. Creating a Triple
You can create a Triple in Kotlin using the Triple constructor.
Using the Triple Constructor
val triple = Triple("Hello", 42, true)
3. Accessing Triple Values
You can access the values of a Triple using the first, second, and third properties.
Example
fun main() {
val triple = Triple("Hello", 42, true)
println("First: ${triple.first}") // Output: Hello
println("Second: ${triple.second}") // Output: 42
println("Third: ${triple.third}") // Output: true
}
4. Triple Functions
The Triple class provides several useful functions:
toList(): Converts the triple to a list.component1(): Returns the first component.component2(): Returns the second component.component3(): Returns the third component.copy(): Creates a copy of the triple with optionally new values for each component.
Example
fun main() {
val triple = Triple("Hello", 42, true)
// Convert to list
val list = triple.toList()
println("List: $list") // Output: [Hello, 42, true]
// Destructure triple
val (first, second, third) = triple
println("First: $first, Second: $second, Third: $third") // Output: Hello, 42, true
// Copy triple with new second value
val newTriple = triple.copy(second = 100)
println("New Triple: $newTriple") // Output: Triple(first=Hello, second=100, third=true)
}
5. Examples of Triple
Example 1: Returning Three Values from a Function
This example demonstrates how to return three values from a function using Triple.
fun getPersonInfo(): Triple<String, Int, String> {
val name = "John Doe"
val age = 30
val city = "New York"
return Triple(name, age, city)
}
fun main() {
val personInfo = getPersonInfo()
println("Name: ${personInfo.first}, Age: ${personInfo.second}, City: ${personInfo.third}")
// Output: Name: John Doe, Age: 30, City: New York
}
Explanation:
This example shows a function that returns a triple of values (name, age, and city) using Triple.
Example 2: Storing Related Values
This example demonstrates how to use Triple to store related values.
fun main() {
val student = Triple("Alice", 20, "Computer Science")
println("Name: ${student.first}, Age: ${student.second}, Major: ${student.third}")
// Output: Name: Alice, Age: 20, Major: Computer Science
}
Explanation:
This example shows how to use Triple to store and print related values (name, age, and major).
Example 3: Using Triple in a List
This example demonstrates how to use Triple in a list to store multiple triples.
fun main() {
val students = listOf(
Triple("Alice", 20, "Computer Science"),
Triple("Bob", 22, "Mathematics"),
Triple("Charlie", 19, "Physics")
)
for (student in students) {
println("Name: ${student.first}, Age: ${student.second}, Major: ${student.third}")
}
}
Output:
Name: Alice, Age: 20, Major: Computer Science
Name: Bob, Age: 22, Major: Mathematics
Name: Charlie, Age: 19, Major: Physics
Explanation:
This example shows how to use Triple to store and print multiple triples in a list.
6. Real-World Use Case: Storing API Response Data
In a real-world scenario, you might need to store multiple pieces of data from an API response using Triple.
Example: Storing API Response Data
fun getApiResponse(): Triple<String, Int, Boolean> {
// Simulate an API response
val responseMessage = "Success"
val responseCode = 200
val isSuccessful = true
return Triple(responseMessage, responseCode, isSuccessful)
}
fun main() {
val apiResponse = getApiResponse()
println("Message: ${apiResponse.first}, Code: ${apiResponse.second}, Success: ${apiResponse.third}")
// Output: Message: Success, Code: 200, Success: true
}
Explanation:
This example simulates an API response and stores the response message, response code, and success status using Triple.
Conclusion
The Triple class in Kotlin is a useful data structure for storing and working with three related values. It provides an easy way to return multiple values from a function, store related values together, and perform various operations on them. Understanding how to use the Triple class can enhance your ability to write clean and efficient Kotlin code.
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