Understanding Pairs and Triples in Kotlin

Understanding Pairs and Triples in Kotlin Kotlin Logo

Understanding Pairs and Triples in Kotlin

Kotlin provides convenient classes like Pair and Triple for handling multiple values together. This blog post will explain how to use these classes effectively with examples.

Let's start with a simple example of using a Pair in Kotlin:


fun main(args: Array<String>) {
    // Creating a Pair in Kotlin
    var (a, b) = Pair("a", 1)
    println("$a, $b")

In the example above, we created a Pair with values "a" and 1. The values are then destructured into variables a and b.

Another way to print the values of a Pair is by accessing its properties:


    // Another way to print the values of a Pair
    var name = Pair("Anmol", 21)
    println("${name.first}, ${name.second}")

We can also nest Pairs inside other Pairs:


    // Pair within a Pair
    var family = Pair("Grandfather", Pair("Father", Pair("Son", "Grand Son")))
    println("${family.first}, ${family.second.first}, ${family.second.second.first}, ${family.second.second.second}")

In this nested Pair example, we have a family hierarchy that is represented as a Pair within another Pair.

Next, let's look at using Triples in Kotlin:


    // Creating a Triple in Kotlin
    var (c, d, e) = Triple("c", 2, 3)
    println("$c, $d, $e")

The above code creates a Triple with values "c", 2, and 3. The values are destructured into variables c, d, and e.

We can also access the values of a Triple using its properties:


    // Another way to print the values of a Triple
    var name1 = Triple("Anmol", 21, "Garg")
    println("${name1.first}, ${name1.second}, ${name1.third}")

Just like Pairs, we can nest Triples within other Triples:


    // Triple within a Triple
    var family1 = Triple("Grandfather", Triple("Father", Triple("Son", "Grand Son", "Great Grand Son"), "3G Son"), "4G Son")
    println("${family1.first}, ${family1.second.first}, ${family1.second.second.first}, ${family1.second.second.second}, ${family1.second.third}, ${family1.third}")

In this nested Triple example, we represent a more extended family hierarchy using a Triple within another Triple.

Pairs and Triples are particularly useful when you need to return multiple values from a function:


    // Example of a function returning multiple values using a Pair
    fun getPersonInfo(): Pair<String, Int> {
        return Pair("Anmol", 21)
    }

    val personInfo = getPersonInfo()
    println("${personInfo.first}, ${personInfo.second}")

In this example, the function getPersonInfo returns a Pair containing a name and an age.

Similarly, you can use a Triple to return three values from a function.

Overall, Pairs and Triples provide a simple and effective way to handle multiple values together in Kotlin.

Post a Comment

Previous Post Next Post