Android Kotlin 从入门到精通(六、扩展函数)

Kotlin的扩展函数可以让你作为一个类成员进行调用的函数。这样可以很方便的扩展一个已经存在的类

public class demo5_扩展函数 {
    @Test
    fun main() {
        //Kotlin的扩展函数可以让你作为一个类成员进行调用的函数。这样可以很方便的扩展一个已经存在的类
        Jump().test()
        val doubble = Jump().doubble()
        println(doubble)
    }

}

//原本类中没有doubleJump方法
class Jump {
    fun test():Int{return 1}
}
//扩展方法定义,就是在方法的前面加类的前缀
fun Jump.doubble():String{
    return "doubleJump"
}

拓展Sting属性
val String.lastchar:Char get() = this.get(length-1)

println("123555啊".lastchar)// 输出:啊

let扩展函数 类后面加上? 代表参数可能为空 使用的时候注意判空

fun main() {
       testLet("ding") //输出 android ding
    }
fun testLet(str:String?){
//        str.let {
//            val str2 = "android"
//            println(str2+str)
//        }
        //判空方法 当str为空 则不会触发闭包里面的逻辑
        str?.let {
            val str2 = "android"
            println(str2+str)
        }
    }

run 扩展函数
返回值为最后一行的值或者指定的return的表达式 , 在run函数中可以直接访问实例的公有属性和方法

 
fun testRun(jump:Jump):String{
        jump.run {
            jump.doubble()
            doubble()
            "111"//最后一行会当作返回值
            return "222"
        }
    }

apply 拓展 调用某对象的apply函数,在函数范围内,可以任意调用该对象的任意方法,并返回该对象

fun testApply(){
        ArrayList<String>().apply {
            add("111")
            add("222")
        }.run {
            for (s in this) {
                println("apply:${s}")
            }
        }
    }

fun testApply() {
    // fun <T> T.apply(f: T.() -> Unit): T { f(); return this }
    ArrayList<String>().apply {
        add("testApply")
        add("testApply")
        add("testApply")
        println("this = " + this)
    }.let { println(it) }
}

// 运行结果
// this = [testApply, testApply, testApply]
// [testApply, testApply, testApply]

Android 实战 给Int添加绑定点击事件(控件id就是用Int值来记录)

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        R.id.btn_binding.Onclick(this){
            println("btn click")
        }
    }
}
fun Int.Onclick(activity: Activity, click: () -> Unit){
    activity.findViewById<View>(this).setOnClickListener {
        println("点击了")
        click()
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值