Kotlin Triple

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

  1. What is the Triple Class?
  2. Creating a Triple
  3. Accessing Triple Values
  4. Triple Functions
  5. Examples of Triple
  6. Real-World Use Case
  7. 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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare