Kotlin Pair

Introduction

In Kotlin, the Pair class is used to store two related values. It is a simple data structure that holds a pair of values, which can be of different types. The Pair class is useful when you need to return two values from a function, or when you want to group two related values together.

Table of Contents

  1. What is the Pair Class?
  2. Creating a Pair
  3. Accessing Pair Values
  4. Pair Functions
  5. Examples of Pair
  6. Real-World Use Case
  7. Conclusion

1. What is the Pair Class?

The Pair class in Kotlin is a generic class that holds two values, often referred to as first and second. It is defined as:

data class Pair<out A, out B>(val first: A, val second: B)

2. Creating a Pair

You can create a Pair in Kotlin using the Pair constructor or the to infix function.

Using the Pair Constructor

val pair = Pair("Hello", 42)

Using the to Infix Function

val pair = "Hello" to 42

3. Accessing Pair Values

You can access the values of a Pair using the first and second properties.

Example

fun main() {
    val pair = "Hello" to 42
    println("First: ${pair.first}")
    println("Second: ${pair.second}")
}

Output:

First: Hello
Second: 42

4. Pair Functions

The Pair class provides several useful functions:

  • toList(): Converts the pair to a list.
  • component1(): Returns the first component.
  • component2(): Returns the second component.

Example

fun main() {
    val pair = "Hello" to 42

    // Convert to list
    val list = pair.toList()
    println("List: $list")

    // Destructure pair
    val (first, second) = pair
    println("First: $first, Second: $second")
}

Output:

List: [Hello, 42]
First: Hello, Second: 42

5. Examples of Pair

Example 1: Returning Two Values from a Function

This example demonstrates how to return two values from a function using Pair.

fun calculate(a: Int, b: Int): Pair<Int, Int> {
    val sum = a + b
    val product = a * b
    return Pair(sum, product)
}

fun main() {
    val (sum, product) = calculate(3, 4)
    println("Sum: $sum, Product: $product")
}

Output:

Sum: 7
Product: 12

Explanation:
This example shows a function that returns a pair of values (sum and product) using Pair.

Example 2: Storing Related Values

This example demonstrates how to use Pair to store related values.

fun main() {
    val capitalCities = listOf(
        "India" to "New Delhi",
        "USA" to "Washington, D.C.",
        "Japan" to "Tokyo"
    )

    for (pair in capitalCities) {
        println("The capital of ${pair.first} is ${pair.second}")
    }
}

Output:

The capital of India is New Delhi
The capital of USA is Washington, D.C.
The capital of Japan is Tokyo

Explanation:
This example shows how to use Pair to store and print related values (country and capital city).

Example 3: Using Pair in a Map

This example demonstrates how to use Pair in a map.

fun main() {
    val coordinates = mapOf(
        "A" to Pair(1, 2),
        "B" to Pair(3, 4),
        "C" to Pair(5, 6)
    )

    for ((key, value) in coordinates) {
        println("Point $key: x=${value.first}, y=${value.second}")
    }
}

Output:

Point A: x=1, y=2
Point B: x=3, y=4
Point C: x=5, y=6

Explanation:
This example shows how to use Pair to store and print coordinates in a map.

6. Real-World Use Case: Parsing URL Parameters

In a real-world scenario, you might need to parse URL parameters and store them as key-value pairs using Pair.

Example: Parsing URL Parameters

fun parseUrlParams(url: String): List<Pair<String, String>> {
    val params = url.substringAfter("?").split("&")
    return params.map {
        val (key, value) = it.split("=")
        key to value
    }
}

fun main() {
    val url = "https://example.com?name=John&age=30&city=New+York"
    val params = parseUrlParams(url)

    for ((key, value) in params) {
        println("$key: $value")
    }
}

Output:

name: John
age: 30
city: New York

Explanation:
This example parses URL parameters into a list of pairs and prints each key-value pair.

Conclusion

The Pair class in Kotlin is a useful data structure for storing and working with two 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 Pair class can enhance your ability to write clean and efficient Kotlin code.

Comments