高阶函数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
}






网友评论