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:
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.")
}
In the below examples, we will create a pair by using the constructor.
Example 1:
Output:
Example 2:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer