解构声明


先来看看一个例子,这是我们在data class 中学会的,两种结构方式,爽歪歪

fun BaseMain() {
    var stu = StudentModel("Niebin", 29)
    var (name, age) = stu
    println("I am a student,my name is $name , I am $age years old.")
    println("Component1= ${stu.component1()} and Component2 = ${stu.component2()}")

}

data class StudentModel(var name: String, var age: Int)

/**打印
I am a student,my name is Niebin , I am 29 years old.
Component1= Niebin and Component2 = 29
*/

方法返回多个值

定义的时候其实也是一个,只是当我们调用时,可以解构一下

fun BaseMain() {
    var (a, b) = multiFun()
    println("a = $a and b = $b")//打印 a = A and b = B
}

data class Mode(var n: String, var a: String)

fun multiFun(): Mode {
    return Mode("A", "B")
}

Map

在lib中,map已经定义了compentN 方法,所以可以在for- in 当中自由使用

   var map: Map<String, Any?> = mapOf("A" to 1, "B" to 2, "C" to 3)
    for ((key, value) in map) {
        println("The key is $key and the value is $value")
    }
    /**
The key is A and the value is 1
The key is B and the value is 2
The key is C and the value is 3
    */

下划线

如果你不用某个解构参数,则可以直接用下划线“_”代替

    var map: Map<String, Any?> = mapOf("A" to 1, "B" to 2, "C" to 3)
    for ((_, value) in map) {
        println("The value is $value")
    }

解构在lambda表达式中

这个没看懂,后期回头看看

results matching ""

    No results matching ""