Kotlin - Destructuring Declarations



Kotlin contains many features of other programming languages. It allows you to declare multiple variables at once. This technique is called Destructuring declaration.

Following is the basic syntax of the destructuring declaration.

val (name, age) = person

In the above syntax, we have created an object and defined all of them together in a single statement. Later, we can use them as follows.

println(name)
println(age)

Now, let us see how we can use the same in our real-life application. Consider the following example where we are creating one Student class with some attributes and later we will be using them to print the object values.

fun main(args: Array<String>) {
   val s = Student("TutorialsPoint.com","Kotlin")
   val (name,subject) = s
   println("You are learning "+subject+" from "+name)
}
data class Student( val a :String,val b: String ){
   var name:String = a
   var subject:String = b
}

The above piece of code will yield the following output in the browser.

You are learning Kotlin from TutorialsPoint.com
Advertisements