How to retrieve values

There are plenty of ways to retrieve values from Pair and Triple, but let's start with simple one. The value of a Pair can be retrieved by assigning it to the following variables:

val (name , price) = mobile

The name variable is assigned with Google and price contains 500 Euros, which is the price of a Google mobile. We can verify this by printing these variables like so:

println("Mobile = $name , Prince = $price Euro")

A Triple can be deconstructed in a similar fashion:

val (name, phone, address) = addressBook
println("Name = $name , Phone = $phone , Address = $address")

There is another way to decompose the Pair and Triple classes. Each member of the Pair and Triple is assigned a name. The first element of the Pair can be accessed by using the property name first, the second with second, and in a Triple, the third element can be accessed with the property name third. For example, create a Pair and Triple of different types. Assign and retrieve the values as follows:

val mobile = Pair("Google", 500)
val
(name , price) = mobile
println("Mobile = ${mobile.first} , Prince = ${mobile.second}")

val addressBook = Triple("Khan", 123456789, "Stockholm")
val
(name, phone, address) = addressBook
println("Name = ${addressBook.first} , Phone = ${addressBook.second} , Address = ${addressBook.third}")

Kotlin also provides a default function for each element—component1() for the first element, component2() for the second element, and so on:

val (p_name, p_phone, p_address) = addressbook
println
("Name = ${addressbook.component1()} , Phone = ${addressbook.component2()} , Address = ${addressbook.component3()}")

While retrieving these values, if any are not required, we can ignore them by using the underscore symbol. See the following example:

val coordinates = Triple(5 , 9 , 11)
val (x, y , _) = coordinates

The coordinates variable contains three values, but by using the underscore symbol, we have simply ignored the z coordinate. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109