美文网首页
Kotlin---operator操作符使用场景

Kotlin---operator操作符使用场景

作者: lewis2017 | 来源:发表于2018-10-30 16:01 被阅读0次

1、对象结构

class Cat(var name:String,var gender:String){

//使用operator关键字定义了两个函数

//需要注意的是,函数的名称一定是 component+数字()

//这时,如果调用了component1,那么得到的就是name

//接下来去看 主方法类,Main类

    operator fun component1() =name

    operator fun component2() =gender

}

使用:

val cat =Kotlin.Cat("Tom", "boy")

//注意这里的赋值

//括号中可以包含任意个元素

//这里有两个,就分别对应 component1() 和 component2()

//如果有第三个,那么就应该对应 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."

相关文章

网友评论

      本文标题:Kotlin---operator操作符使用场景

      本文链接:https://www.haomeiwen.com/subject/flbgtqtx.html