English 中文(简体)
Kotlin - Destructuring Declarations
  • 时间:2024-11-03

Kotpn - Destructuring Declarations


Previous Page Next Page  

Kotpn 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-pfe apppcation. 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","Kotpn")
   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 Kotpn from TutorialsPoint.com
Advertisements