Kotlin擴展

package com.hand.test

fun main(args: Array<String>) {
    val list = mutableListOf(1, 2, 3)
    list.swap(0, 2)
    println("list.swap(0,2):$list")
    val str = "1234"
    println("lastChar is ${str.lastChar}")
    Jump.print("1234567")
    testLet("123")
    testLet(null)
    testApply()
}

//方法擴展
fun MutableList<Int>.swap(index1: Int, index2: Int) {
    val temp = this[index1]
    this[index1] = this[index2]
    this[index2] = temp
}

//泛型擴展方法
fun <T> MutableList<T>.swap2(index1: Int, index2: Int) {
    val temp = this[index1]
    this[index1] = this[index2]
    this[index2] = temp
}

//擴展屬性
//為String添加一個lastChar屬性,用于獲取字符串的最后一個字符
val String.lastChar: Char get() = this.get(this.length - 1)

//伴生對象擴展
class Jump {
    companion object {}
}

fun Jump.Companion.print(str: String) {
    println("jump $str")
}

/*
*let擴展
*/
fun testLet(str: String?) {
    //避免為null的操作
    str?.let {
        println(it.length)
    }
    //限制作用域
    str.let {
        val str2 = "let作用域"
    }
}


data class Room(val address: String, val price: Float, val size: Float)

/*
*run擴展
* 函數原型 fun<T,R> T.run(f: T.() -> R):R = f()
* run函數只接收-個lamda函數作為參數,以閉包形式返回,返回值為最后一行的值或者指定的return的表達式,
* 在run函數可以直接訪問實例的公有屬性和公有方法
*/
fun testRun(room: Room) {
    /*room.address
    room.price
    room.size*/
    //在run的代碼塊里可以直接訪問其屬性
    room.run {
        println("Room:$address,$price,$size")
    }
}

/*
*apply 擴展
* 函數原型
* fun<T> T.apply(f: T.()->Unit):T{f();return this}
* apply函數的作用是:調用某對象的apply函數,在函數范圍內,可以任意調用該對象的任意方法
* 并返回該對象。類似于Builder
*/

fun testApply() {
    ArrayList<String>().apply {
        add("1")
        add("2")
    }.let {
        println(it)
    }
}

/*------案例:使用Kotlin擴展為控件綁定監聽器減少模版代碼------*/
//為Activity添加find擴展方法,用于通過資源id獲取控件
fun <T : View> Activity.find(@IdRes id: Int): T {
    return findViewById(id)
}

//為Int添加onClick擴展方法,用于為資源id對應的控件添加onClick監聽
fun Int.onClick(activity: Activity, click: () -> Unit) {
    activity.find<View>(this).apply{
        setOnClickListener{
            click()
        }
    }

}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。