Kotlin笔记 第七章 (二)解构.md

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Leslie_LN/article/details/82863030

解构

1、

将对象N个属性解构给多个变量,如:
var (name,pass)=user(对象)

要解构多少属性给变量,对象类必须至少定义多少个componentN(N从1开始)方法,并且该方法必须使用operator修饰;这儿为什么说至少呢?因为左边变量个数可以小于componentN方法个数,即只是将需要的属性解构给变量;

如:

class Dog constructor() {
    var name:String="leslie"


    var age:Int=10

    fun run() {
        println("run方法")
    }

    fun eat(food: String) {
        println("正在吃:${food}")

    }
    fun sleep(){
        println("正在睡觉")
    }
    operator fun component1():String{
        return this.name

    }
    operator  fun component2():Int{
        return this.age
    }




}

1、将所有属性解构给变量:

		var (name,age)=Dog()

会将component1()方法返回变量结构给name,会将component2()返回的属性解构变量age;

2、将部分属性结构给变量:

	var(name)=Dog()

只会将component1()解构给name变量

3、将后面的componentN()解构变量,前面的不用解构给变量,可以使用“_”占位符:

var (_,age)=Dog()

这是就只会将component2()方法返回值解构给age属性

猜你喜欢

转载自blog.csdn.net/Leslie_LN/article/details/82863030
今日推荐