1、對象結(jié)構(gòu)
class Cat(var name:String,var gender:String){
//使用operator關(guān)鍵字定義了兩個函數(shù)
//需要注意的是,函數(shù)的名稱一定是 component+數(shù)字()
//這時趋翻,如果調(diào)用了component1,那么得到的就是name
//接下來去看 主方法類褂删,Main類
? ? operator fun component1() =name
? ? operator fun component2() =gender
}
使用:
val cat =Kotlin.Cat("Tom", "boy")
//注意這里的賦值
//括號中可以包含任意個元素
//這里有兩個您宪,就分別對應(yīng) component1() 和 component2()
//如果有第三個,那么就應(yīng)該對應(yīng) component3() 方法
val (name,gender) =cat
2芍躏、屬性代理
class Example {
? ? var p: String by Delegate()
}
代理類:
class Delegate {
? ? operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
? ? ? ? return "$thisRef, thank you for delegating '${property.name}' to me!"
? ? }
? ? operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
? ? ? ? println("$value has been assigned to '${property.name} in $thisRef.'")
? ? }
}
使用:
val e = Example()
println(e.p) // will print "Example@33a17727, thank you for delegating ‘p’ to me!"
e.p = "NEW" // will print "NEW has been assigned to ‘p’ in Example@33a17727."