Q:

Kotlin example of creating pair using the constructor

belongs to collection: Kotlin Pair Programs

0

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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program to retrieve the values of Pair usin... >>