Kotlin 简明教程
Kotlin - Destructuring Declarations
Kotlin 包含了许多其他编程语言的功能。它允许你同时声明多个变量。此技术称为解构声明。
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