Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What is a pair in Kotlin?

Victor Elezua

Sometimes, we may need a function to return multiple values after a task. In Kotlin, we can do something like this:

data class Rect(val length: Int, val width: Int)

Our function can now return a new instance of the Rect data class:

fun getReactangle(): Rect {
    // some computation
    return Rect(20, 4)
}

This approach is common and works fine.

How to use the Pair object to return two values

You might work on an application that needs to return two values. This can have many use-cases, such as canvas dimensions and location. If we go with the initial approach of creating a data class, we can easily create tens (if not up to hundreds) in a fairly complex application, when we should actually try to reuse and write less code.

data class Dimension(
    val width: Int,
    val height: Int,
)

data class Location(
    val long: Double,
    val lat: Double,
)

fun getCanvasDimension(): Dimension {
    // some code
    return Dimension(10, 20)
}

fun getCurrentLocation(): Location {
    // some code
    return Location(4.54739, 9.01127)
}

We can use the Pair object to avoid creating multiple data classes.

To create a Pair object, call the class constructor Pair(first: A, second: B). A and B in the constructor signature signify that you are not restricted to a particular type, and you can take advantage of Kotlin’s generics features here, e.g. val rect = Pair<Int, Long>(90, 70000). We can explicitly set the types we want to work with. In the initial constructor example, the types are inferred.

fun getCanvasDimension(): Pair<Int, Int> {
    // some code
    return Pair(10, 20)
}

fun getCurrentLocation(): Pair<Double, Double> {
    // some code
    return Pair(4.54739, 9.01127)
}

We can access the properties of the Pair object by calling .first to get the first value or .second on the object to get the second value.

Now, we don’t need to write and keep track of many classes.

More on the Pair class

data class Pair<out A, out B>: Serializable

From the class signature above, we can see that Pair is a generic class and implements the Serializable interface. Serializable objects in Android can be passed to Android components such as Fragments, Activities, or Services via the Bundle object.

In conclusion, Pair can be used as a tuple of two homogeneous or heterogeneous values.

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring