The Pair data class in Kotlin to store even values

- Andrés Cruz

En español
The Pair data class in Kotlin to store even values

Continuing with the Kotlin tutorials, today we will see the Pair data class in Kotlin, which is simply a generic representation (any data type or class) of two values (pairs).

Pair class data is a structure that allows two values to be stored.

To use even values in Kotlin we can do the following:

var pair = Pair("Kotlin Pair",2)

We can also create even values using the reserved variable to as follows:

var pair = "Kotlin Pair" to 2

This is very useful in Android since we can use the Pair to store a pair of values, for example a username and password or any pair of values that have a relationship.

How to access Pair values in Kotlin?

Having clear what the structure of the Pair in Kotlin is for, the next thing we are interested in knowing is how to access each of these embedded values within a Pair data class; for this, the reserved words first and second are used respectively in the following way; having our variable named pair defined in any of the above ways:

println(pair.first) //Kotlin
println(pair.second) //Pair2

And we get as output:

Kotlin Pair2

For each of the println respectively.

Decomposition of Pair values in Kotlin

We can also separate or decompose the values of the pairs into individual and independent variables in the following way; as we did before with the same data class in the previous entry:

val (user, password) = Pair("usuario", "contrasena") 
println(user) // usuario
println(password) // contrasena

And you get:

usuario contrasena

Always remember to review the official documentation at: Kotlin: Pair and Kotlin: To.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.