Kotlin - Destructuring Declarations


Advertisements

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

Useful Video Courses


Video

Kotlin Online Training

68 Lectures 4.5 hours

Arnab Chakraborty

Video

Kotlin Masterclass Programming: Android Coding Bible

Featured

71 Lectures 5.5 hours

Frahaan Hussain

Video

Android Dependency Injection using Dagger with Kotlin

18 Lectures 1.5 hours

Mahmoud Ramadan

Video

Android Retrofit complete course in Kotlin

49 Lectures 6 hours

Catalin Stefan

Video

Master Kotlin - Learn Kotlin to develop android apps

49 Lectures 2.5 hours

Skillbakerystudios

Video

Breeze Music Player - Learn Kotlin, MVVM and MediaPlayer API

22 Lectures 1 hours

CLEMENT OCHIENG

Advertisements