Kotlin學習筆記-7 --- 擴充套件
阿新 • • 發佈:2021-05-23
- Kotlin 可以對一個類的屬性和方法進行擴充套件,且不需要繼承或使用 Decorator 模式
- 擴充套件是一種靜態行為,對被擴充套件的類程式碼本身不會造成任何影響
1、函式擴充套件
定義類
class User constructor(var name: String) {
var mName: String = name
}
使用擴充套件函式
class UIActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate (savedInstanceState)
setContentView(R.layout.ac_ui)
val user = User("Alex")
user.showInfo()
}
/**
* 定義 User 的擴充套件函式
*/
private fun User.showInfo() {
Log.i("TAG_ZLZ", "------ name : $mName")
}
}
日誌輸出
- 呼叫擴充套件函式時,具體被呼叫的的是哪一個函式,由呼叫函式的的物件表示式來決定的,而不是動態的型別決定的
open class A {
}
class B : A() {
}
class UIActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ac_ui)
val a = A()
val b = B()
showInfo(a)
showInfo(b)
}
/**
* A 的擴充套件函式
*/
fun A.show() {
Log.i("TAG_ZLZ", "------ A")
}
/**
* B 的擴充套件函式
*/
fun B.show() {
Log.i("TAG_ZLZ", "------ A")
}
fun showInfo(a: A) {
a.show()
}
}
2、屬性擴充套件
- 擴充套件屬性允許定義在類或者kotlin檔案中,不允許定義在函式中
- 初始化屬性因為屬性沒有後端欄位,所以不允許被初始化,只能由顯式提供的 getter/setter 定義
定義
class Person {
/***************** 位置 *****************/
val HashMap<Int, String>.firstPosition: Int
get() = 0
val HashMap<Int, String>.lastPosition: Int
get() = size - 1
val HashMap<Int, String>.midPosition: Int
get() = (firstPosition + lastPosition) / 2
/***************** ID *****************/
val HashMap<Int, String>.firstPersonID: Int?
get() {
val set = this.keys
return set.elementAt(firstPosition)
}
val HashMap<Int, String>.lastPersonID: Int?
get() {
val set = this.keys
return set.elementAt(lastPosition)
}
val HashMap<Int, String>.midPersonID: Int?
get() {
val set = this.keys
return set.elementAt(midPosition)
}
/***************** 姓名 *****************/
val HashMap<Int, String>.firstPersonName: String?
get() {
val set = this.values
return set.elementAt(firstPosition)
}
val HashMap<Int, String>.lastPersonName: String?
get() {
val set = this.values
return set.elementAt(lastPosition)
}
val HashMap<Int, String>.midPersonName: String?
get() {
val set = this.values
return set.elementAt(midPosition)
}
val map = HashMap<Int, String>()
fun test() {
map.put(1001, "Alex")
map.put(2721, "Bob")
map.put(3923, "Cam")
map.put(4001, "Allen")
map.put(5721, "Sam")
Log.i(
"TAG_ZLZ",
"------ 第一人 : ${map.firstPosition}, ${map.firstPersonID}, ${map.firstPersonName}"
)
Log.i(
"TAG_ZLZ",
"------ 中間人 : ${map.midPosition}, ${map.midPersonID}, ${map.midPersonName}"
)
Log.i(
"TAG_ZLZ",
"------ 最後人 : ${map.lastPosition}, ${map.lastPersonID}, ${map.lastPersonName}"
)
}
}
使用
val p = Person()
p.test()
日誌輸出