kotlin: 匿名函数/lambda表达式做参数的常用形式
一,代码
定义的函数:
fun getIsL(char:Char): Boolean {
if ( char == 'l') {
return true
} else {
return false
}
}
调用:
//处理按钮点击事件
binding.button1.setOnClickListener {
//count函数的参数 类型为: predicate: (Char) -> Boolean
// 统计字符串中 l 字符长度
//直接调用lambda表达式的三种形式:
//使用定义的变量
val toalLCount = "Hello".count({ letter->
letter == 'l'
})
println("toalLCount = $toalLCount")
//只有一个参数时可以使用it
val toalLCount2 = "Hello".count({ it == 'l'
})
println("toalLCount2 = $toalLCount2")
//最后一个参数是函数时可以放到()外部
val toalLCount3 = "Hello".count { it == 'l' }
println("toalLCount3 = $toalLCount3")
//定义一个lambda表达式
val isL1 = {char:Char->
char == 'l'
}
//lambda表达式做参数
val toalLCount4 = "Hello".count(isL1)
println("toalLCount4 = $toalLCount4")
//函数的引用做参数
val toalLCount5 = "Hello".count(::getIsL)
println("toalLCount5 = $toalLCount5")
//定义一个匿名函数
val isL = fun(char:Char): Boolean {
if ( char == 'l') {
return true
} else {
return false
}
}
//匿名函数做参数
val toalLCount6 = "Hello".count(isL)
println("toalLCount6 = $toalLCount6")
//匿名函数直接做参数
val toalLCount7 = "Hello".count(fun(char:Char): Boolean {
if ( char == 'l') {
return true
} else {
return false
}
})
println("toalLCount7 = $toalLCount7")
}
二,运行结果:

浙公网安备 33010602011771号