Lesson Overview

In today's lesson, we'll explore Kotlin's approach to data structures, focusing on lists, pairs, and triples. We'll learn how to work with lists to perform operations like filtering and transforming data, and how to use pairs and triples to group related elements together. We'll also explore nested structures that combine these elements to create more complex data organizations. By the end of this lesson, you'll be able to effectively work with these fundamental Kotlin data structures and understand when to use each one.

Understanding Pairs

In Kotlin, a pair is a simple container used to hold two values, which can be accessed using the first and second properties. Pairs are commonly used when you need to return two related items from a function or method.

Consider this Kotlin example that uses a pair:

class PairExample {
    fun createPair(): Pair<String, String> {
        return Pair("apple", "banana")
    }
}

fun main(){
    // create an instance and call the `createPair` method
    val pairExample = PairExample()
    val fruitPair = pairExample.createPair()
    println(fruitPair)            // Output: (apple, banana)
    println(fruitPair.first)      // Output: apple
    println(fruitPair.second)     // Output: banana
    // Attempting to change the values directly will cause an error
    // fruitPair.first = "orange" // This line would cause a compilation error
}

In this example, the PairExample class contains a method createPair that returns a pair of strings. These are then printed, along with each element accessed individually using first and second. A pair in Kotlin is inherently immutable, meaning once you create it, you cannot change its first and second values. This immutability ensures that the data held within a pair remains constant, providing safety when working with concurrent or multithreaded applications.

Understanding Triples

Kotlin provides a Triple class, which is similar to Pair but holds three values. It's useful when you need to manage three related items together:

fun main(){
    val coordinates = Triple(3.5, 7.0, 1.5)
    println(coordinates)            // Output: (3.5, 7.0, 1.5)
    println(coordinates.first)      // Output: 3.5
    println(coordinates.second)     // Output: 7.0
    println(coordinates.third)      // Output: 1.5
}

In this example, the Triple instance coordinates holds three Double values representing spatial coordinates. Similar to pairs, triples are immutable, meaning once they are created, their values cannot be changed. This immutability ensures data consistency, making Triple a reliable choice for handling three grouped items.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal