ADVERTISEMENT
ADVERTISEMENT

Kotlin example of creating pair using the constructor

Example to create pair using the constructor in Kotlin.
Submitted by IncludeHelp, on April 02, 2022

In Kotlin, the constructor is the same as in other programming languages, it is a special kind of member function that is invoked when an object is being created and it is primarily used for initializing the variables or properties.

Here is the syntax to create a new instance of the Pair:

Pair(first: A, second: B)

In the below examples, we will create a pair by using the constructor.

Example 1:

fun main() {
	// creating a new instance of the Pair
	val (a, b) = Pair(10, 20)

	// Printing the values
	println(a)
	println(b)
}

Output:

10
20

Example 2:

fun main() {
	// creating a new instance of the Pair
	val (name, age) = Pair("Alvin Alexander", 35)

	// Printing the values
	println("The name is $name.")
	println("And, the age is $age.")
}

Output:

The name is Alvin Alexander.
And, the age is 35.

Kotlin Pair Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.