Pair in Kotlin

Learn via video courses
Topics Covered

Overview

Kotlin offers a rich set of features that enhance developer productivity. One such feature is the Pair class, a versatile and efficient way to work with two related values as a single unit. In this article, we will delve into the Pair in Kotlin, exploring its syntax, usage, and benefits for creating more readable and concise code.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

What is Pair in Kotlin?

Pair in Kotlin is a standard library class that represents a simple tuple of two values. Pair in Kotlin is a generic class, allowing you to define the types of its two components independently. The primary purpose of Pair in Kotlin is to group two values together, providing a convenient way to work with related data as a single entity.

Creating and Using Pairs in Kotlin

Class Definition

where:

  • A
    type of the first value

  • B
    type of the second value

Constructor

In Kotlin, a constructor is a special member function that gets called when an object of a class is being created, mainly for the purpose of initializing variables or properties. To instantiate a new object of the Pair in Kotlin, the following constructor is used.

Code:

Here's an example demonstrating the creation of a Pair in Kotlin using the constructor.

Code:

Output:

Explanation:

In this example, a Pair in Kotlin is instantiated with values 1 and "Shubham", and the main() function uses destructuring declarations to assign these values to variables x and y, respectively.

Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

Properties

The values within a pair can be obtained either by assigning them to a single variable or by utilizing the first and second properties for extraction.

  • first:
    This property holds the first value of the pair.
  • second:
    This property stores the second value of the pair.

Here's a program illustrating how to access the values of a pair in Kotlin using these properties.

Code:

Output:

Explanation:

In this example, a Pair in Kotlin is declared with the values 1 and "Shubham".

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Functions

One of the functions available for the Pair in Kotlin is toString(), which provides the string representation of the pair.

  • toString():
    This function returns a string equivalent of the pair.

Here's a program showcasing the usage of the toString() function with a pair in Kotlin:

Code:

Output:

Explanation:

In this example, two pairs are created – one with character values and another with a string and a list. The toString() function is then applied to each pair, and the resulting string representations are printed. This function is useful for obtaining a readable representation of the Pair instance.

Extension Functions

Extension functions empower us to add the functionalities of existing classes without the need for inheritance.

  • toList():
    This extension function returns the List equivalent of a given Pair in Kotlin.

The declaration of the extension function is as follows.

Code:

Now, let us see a Kotlin program that uses this extended function on a pair in Kotlin.

Code:

Output:

Explanation:

In this example, three pairs are created – with character values, integer values and with strings. The toList() extension function is then applied to each pair, converting them into lists. The resulting lists (list1, list2, list3) are printed. This extension function enhances the versatility of the Pair in Kotlin by allowing it to be transformed into a List.

Advantages of Using Pairs in Kotlin

  • Pair in Kotlin provides a concise and readable way to represent and work with pairs of values. The syntax is straightforward, contributing to more readable code.
  • Kotlin's support for destructuring declarations allows developers to easily extract values from a Pair in Kotlin into separate variables, enhancing code readability and reducing verbosity.
  • Developers can extend the functionality of the Pair in Kotlin using extension functions like toList(), allowing for additional operations or conversions. This enhances the flexibility of working with pairs.
  • Pair in Kotlin provides a human-readable toString() representation, making it easier to debug and log the content of pairs during development.
  • Pair in Kotlin is versatile and can be used to represent pairs of values of different types, making it applicable in various scenarios where related data needs to be grouped together.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Triple: An Extension of Pair in Kotlin

In Kotlin, a Triple is an extension of the Pair class, allowing developers to work with three related values as a single unit. Similar to Pair, Triple provides a convenient way to group and manage a triplet of data in a concise manner. Here's an overview of the Triple class:

Declaration

The Triple class is declared as a generic data class that can hold three values of potentially different types.

Code:

Initialization

Code:

Accessing Elements:

Individual elements of a Triple can be accessed using the .first, .second, and .third properties.

Code:

Conclusion

Here are the key conclusions of this article on Pair in Kotlin:

  • The Pair in Kotlin enhances code readability by providing a concise way to represent and work with pairs of related data, contributing to clearer and more expressive code.
  • The support for destructuring declarations simplifies the extraction of values from a Pair in Kotlin, reducing boilerplate code and making the codebase more readable.
  • Pair in Kotlin is a versatile class that can hold pairs of values of different types, making it applicable in various scenarios where related data needs to be grouped together.
  • Instances of Pair are immutable, ensuring stability and predictability in code. Once created, the values within a Pair cannot be modified, contributing to code reliability.
  • Pair in Kotlin is commonly used to return multiple values from functions, offering a convenient way to encapsulate and convey related data in a single return type.
  • Through extension functions like toList(), developers can customize the functionality of Pair in Kotlin, making it adaptable to specific use cases and increasing its utility in diverse scenarios.