Home »
Kotlin »
Kotlin Programs
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 »