2021-12-03(Kotlin学习笔记)高阶函数(apply 、also、let以及实践))

高阶函数apply

//默认 无参数
fun <T> T.myApply(mm: () -> Unit) : T{
    // T == this
    mm()
    return this
}

高阶函数also

fun <T> T.myAlso(mm: (T) -> Unit) : T{
    // T == this
    // it == T == this == name
    mm(this)
    return this
}

高阶函数let

// it == T == this == 参数
fun <T, R> T.myLet(mm: (T) -> R) : R{
    return mm(this)
}

fun <T, R> T.myLet1(mm: (T) -> R) : R = mm(this)

//不想要it, 给T增加匿名的扩展函数,并且此函数 行参是T
fun <T, R> T.myLet2(mm: T.(T) -> R) : R {
    return mm(this)
}

myLet 、myLet2区别(入参(T)/T.(T))(myLet it/myLet2 it)


image.png

实际应用 自定义线程以及轮询器

un main() {

    ktRun(){
        doCounts(9){
            println("自定义线程$it")
        }
    }
}

//自定义轮询器
fun doCounts(counts: Int, mm:(Int) -> Unit){
    for(index: Int in 0 until counts){
        mm(index)
    }
}

//自定义线程
fun ktRun(start: Boolean = true,
          name: String = "bsm",
          mRunAction: () -> Unit) : Thread{
    val thread = object : Thread(){
        override fun run() {
            super.run()
            mRunAction()
        }
    }
    if(start){
        thread.start()
    }
    return thread
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容