Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Kotlin Basics : What are pairs and triplets

Devrath edited this page Jan 1, 2024 · 2 revisions
Screenshot 2023-12-24 at 9 44 43β€―AM

About pairs and triplets

  • They are groups of two to three pieces of data.
  • They can represent classes or pieces of data.

Storing in pairs

  • This accepts two inputs it can be anything primitive-type, non-primitive-type, objects, collections , etc..
  • So basically there are two parts
  • Both parts can be of different type meaning ex: one can be int and another can be string etc..

Sample of constructing a pair

private fun initiate() {
        var fullName : Pair<String,String> = Pair("Tony","Stark")
        println("My name is ${fullName.first} ${fullName.second}")

        var studentDetails : Pair<Student,Address> = Pair(Student("Tony","21"),
                                                          Address("HSR layout","Bangalore"))
        println("Super hero name is ${studentDetails.first.name} and from the place ${studentDetails.second.city}")
}

Sample of destructing a pair

private fun initiate() {
        var fullName : Pair<String,String> = Pair("Tony","Stark")
        var (firstName,lastName) = fullName
        println("My name is $firstName $lastName")
}

Using Triple

  • Using tripe is similar to pair.
  • Only difference is that it can hold three types in its three placeholders.
  • Destructing the triple is the same as the pair mentioned above.
 private fun initiateSecond() {
        var fullName : Triple<String,String,String> = Triple("Tony","Stark","Bangalore")
        var (firstName,lastName,place) = fullName
        println("My name is $firstName $lastName from the place $place")
}

Clone this wiki locally

Morty Proxy This is a proxified and sanitized view of the page, visit original site.