無需依靠繼承和裝飾者模式來擴展一個類的功能,通過擴展的特殊聲明實現
可以通過擴展函數替代工具類
一、擴展函數
- 把一個類的類名作爲前綴,在函數內可以直接使用該類的對象
this
。如擴展Activity
的功能
fun Activity.startActivity(cls: Class<*>) {
startActivity(Intent(this, cls))
}
- 擴展函數是靜態的。擴展沒有實際修改他們所擴展的類,並沒有給原有的類插入新的成員,即他的值是被引用時的對象類型決定。編譯器會提醒
open class Person
class Student: Person()
fun Person.name() = "person"
fun Student.name() = "student"
fun printPerson(person: Person){
println(person.name())
}
fun main() {
// 打印爲 person
printPerson(Student())
}
- 擴展函數和成員函數的名稱、參數列表、返回值相同時,調用的是成員函數。編譯器會提醒
class Person{
fun play(){ }
}
fun Person.play(){ }
二、擴展屬性
把一個類的類名作爲前綴,通過 get()/set()
擴展一個類的屬性
class Person
val Person.name: String
get() = "wmj"
// 編譯出錯。Extension property cannot be initialized because it has no backing field
val Person.name: String = "wmj"