10.Kotlin扩展作用域分析与扩展的根本作用解析

2017-12-24  本文已影响0人  leofight

1.扩展属性

与函数类似,Kotlin支持扩展属性。

class MyExtensionProperty

val MyExtensionProperty.name: String
    get() = "hello"


fun main(args: Array<String>) {
    var myExtensionProerty = MyExtensionProperty();
    println(myExtensionProerty.name)
}
hello

2.伴生对象扩展


class CompanionObjectExtension {
    companion object MyObject {

    }
}

fun CompanionObjectExtension.MyObject.method() {
    println("hello world")
}

fun main(args: Array<String>) {
    CompanionObjectExtension.method()
}
hello world

3.扩展的作用域

扩展的作用域
①扩展函数所定义的类实例叫做分发接收者(dispatch receiver)
②扩展函数所扩展的那个类的实例叫做扩展接收者(extension receiver)
③当以上两个名字出现冲突时,扩展接收者的优先级最高。

class DD {
    fun method() {
        println("DD method")
    }
}

class EE {
    fun method2() {

    }

    //对DD扩展
    fun DD.hello() {
        method()
        method2()
    }

    fun world(dd: DD) {
        dd.hello()
    }

    fun DD.output() {
        println(toString())
        println(this@EE.toString())
    }

    fun test() {
        var dd = DD()
        dd.output()
    }
}

fun main(args: Array<String>) {
    EE().test()


}
com.leofight.kotlin.DD@7440e464
com.leofight.kotlin.EE@49476842

扩展可以很好地解决Java中充斥的各种辅助类问题
Collections.swap(list,4,10)
list.swap(4,10) //这样语义更明确,可使用kotlin扩展
Collection.binarySearch()
list.binarySearch(...)//这样语义更明确,可使用kotlin扩展

上一篇 下一篇

猜你喜欢

热点阅读