🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In Kotlin, the Pair class is used to store two related values. It is a simple data structure that holds a pair of values, which can be of different types. The Pair class is useful when you need to return two values from a function, or when you want to group two related values together.
Table of Contents
- What is the
PairClass? - Creating a
Pair - Accessing Pair Values
- Pair Functions
- Examples of
Pair - Real-World Use Case
- Conclusion
1. What is the Pair Class?
The Pair class in Kotlin is a generic class that holds two values, often referred to as first and second. It is defined as:
data class Pair<out A, out B>(val first: A, val second: B)
2. Creating a Pair
You can create a Pair in Kotlin using the Pair constructor or the to infix function.
Using the Pair Constructor
val pair = Pair("Hello", 42)
Using the to Infix Function
val pair = "Hello" to 42
3. Accessing Pair Values
You can access the values of a Pair using the first and second properties.
Example
fun main() {
val pair = "Hello" to 42
println("First: ${pair.first}")
println("Second: ${pair.second}")
}
Output:
First: Hello
Second: 42
4. Pair Functions
The Pair class provides several useful functions:
toList(): Converts the pair to a list.component1(): Returns the first component.component2(): Returns the second component.
Example
fun main() {
val pair = "Hello" to 42
// Convert to list
val list = pair.toList()
println("List: $list")
// Destructure pair
val (first, second) = pair
println("First: $first, Second: $second")
}
Output:
List: [Hello, 42]
First: Hello, Second: 42
5. Examples of Pair
Example 1: Returning Two Values from a Function
This example demonstrates how to return two values from a function using Pair.
fun calculate(a: Int, b: Int): Pair<Int, Int> {
val sum = a + b
val product = a * b
return Pair(sum, product)
}
fun main() {
val (sum, product) = calculate(3, 4)
println("Sum: $sum, Product: $product")
}
Output:
Sum: 7
Product: 12
Explanation:
This example shows a function that returns a pair of values (sum and product) using Pair.
Example 2: Storing Related Values
This example demonstrates how to use Pair to store related values.
fun main() {
val capitalCities = listOf(
"India" to "New Delhi",
"USA" to "Washington, D.C.",
"Japan" to "Tokyo"
)
for (pair in capitalCities) {
println("The capital of ${pair.first} is ${pair.second}")
}
}
Output:
The capital of India is New Delhi
The capital of USA is Washington, D.C.
The capital of Japan is Tokyo
Explanation:
This example shows how to use Pair to store and print related values (country and capital city).
Example 3: Using Pair in a Map
This example demonstrates how to use Pair in a map.
fun main() {
val coordinates = mapOf(
"A" to Pair(1, 2),
"B" to Pair(3, 4),
"C" to Pair(5, 6)
)
for ((key, value) in coordinates) {
println("Point $key: x=${value.first}, y=${value.second}")
}
}
Output:
Point A: x=1, y=2
Point B: x=3, y=4
Point C: x=5, y=6
Explanation:
This example shows how to use Pair to store and print coordinates in a map.
6. Real-World Use Case: Parsing URL Parameters
In a real-world scenario, you might need to parse URL parameters and store them as key-value pairs using Pair.
Example: Parsing URL Parameters
fun parseUrlParams(url: String): List<Pair<String, String>> {
val params = url.substringAfter("?").split("&")
return params.map {
val (key, value) = it.split("=")
key to value
}
}
fun main() {
val url = "https://example.com?name=John&age=30&city=New+York"
val params = parseUrlParams(url)
for ((key, value) in params) {
println("$key: $value")
}
}
Output:
name: John
age: 30
city: New York
Explanation:
This example parses URL parameters into a list of pairs and prints each key-value pair.
Conclusion
The Pair class in Kotlin is a useful data structure for storing and working with two related values. It provides an easy way to return multiple values from a function, store related values together, and perform various operations on them. Understanding how to use the Pair class can enhance your ability to write clean and efficient Kotlin code.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment