Kotlin program to get the string equivalent of the Pair

Learn how to get the string equivalent of the Pair using toString() function?
Submitted by IncludeHelp, on April 02, 2022

In the below given examples, we will create Pair using the constructor and demonstrate how to get the string equivalent of the Pair using the toString() function?

toString() function:

The toString() function returns string representation of the Pair including its first and second values.

Syntax:

fun toString(): String

Consider the below examples –

Example 1:

fun main() {
	// creating a new instance of the Pair
	val pair1 = Pair(10, 20)
	println("String representation of pair1 : "+pair1.toString())

	val pair2 = Pair("Alvin Alexander", 35)	
	println("String representation of pair2 : "+pair2.toString())
}

Output:

String representation of pair1 : (10, 20)
String representation of pair2 : (Alvin Alexander, 35)

Example 2:

fun main() {
	// creating a new instance of the Pair
	// Here, first value is the string and 
	// the second value is the list of strings
	val pair1 = Pair("Developers", listOf("Alvin", "Alex", "David"))

	// String representation using toString() function
	println("String representation of pair1 : "+pair1.toString())

	// creating a new instance of the Pair
	// Here, first value is the list of strings (names)
	// the second value is the list of integers (ages)
	val pair2 = Pair(listOf("Alvin", "Alex", "David"), listOf(20, 25, 30))

	// String representation using toString() function
	println("String representation of pair2 : "+pair2.toString())    
}

Output:

String representation of pair1 : (Developers, [Alvin, Alex, David])
String representation of pair2 : ([Alvin, Alex, David], [20, 25, 30])

Kotlin Pair Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.