Kotlin can break an object into multiple variables, an operation called deconstruction declaration
Define a simple data class
data class Person(var name: String, var age: Int)
fun main(a) {
val person = Person("zhangsan".1)
println("- >${person.name}")
println("- >${person.age}")
val (name, age) = person
println("- >$name")
println("- >$age")}/ / output
-> zhangsan
-> 1
-> zhangsan
-> 1
Copy the code
The name and age variables output the corresponding attribute values, which greatly simplifies our operation.
Data classes can use destruct declarations because data classes are special, and the compiler declares the following functions for them by default:
@NotNull
public final String component1(a) {
return this.name;
}
public final int component2(a) {
return this.age;
}
Copy the code
Assigning values for name and age is equivalent to calling component1 and Component2 of the object respectively, which is the core principle of deconstruction declaration.
Custom deconstruction declarations
Normal classes do not have the capability to destruct. We can manually declare componentN(). We need the operator modifier:
class Book(var title: String, var price: Float) {
operator fun component1(a): String = title
operator fun component2(a): Float = price
}
fun main(a) {
val book = Book("The ordinary world.".19.9 f)
println("- >${book.title}")
println("- >${book.price}")
val (title, price) = book
println("- >$title")
println("- >$price")}/ / output-> Ordinary world ->19.9-> Ordinary world ->19.9
Copy the code
Array, collection deconstruction declaration
By default, Kotlin supports deconstruction declarations for arrays, lists, and maps
fun main(a) {
val array = arrayOf(1.2.3)
val (a, b, c) = array
println("-> a: $a b: $b c: $c")
val list = listOf(1.2.3)
val (d, e, f) = list
println("-> d: $d e: $e f: $f")
val map = mapOf("key1" to 1."key2" to 2."key3" to 3)
for ((key, value) in map) {
println("- >$key : $value")}}/ / output
-> a: 1 b: 2 c: 3
-> d: 1 e: 2 f: 3
-> key1 : 1
-> key2 : 2
-> key3 : 3
Copy the code
A deconstruction declaration in a Lambda expression
We can deconstruct an argument in a Lambda expression. First, the argument must meet the condition that it can be deconstructed:
fun main(a) {
val book = Book("gone with the wind".10.0 f)
showBookInfo(book) { (name, price) ->
println("-> name: $name")
println("-> price: $price")}}fun showBookInfo(book: Book, block: (Book) - >Unit) {
book.run(block)
}
Copy the code