1、lambda 表达式
//lambda表达式
val b: (Int) -> Boolean = { it > 0 }
val c = {x:Int -> x>0}
val b1: (Int,Int) -> Boolean = { x,y -> x>y }
println(b(-1))
println(c(-1))
2、函数式接口
也叫做 SAM (单抽象方法)编程 一个接口一个方法
fun interface IntPredata {
fun getInt(num: Int): Int
}
val a = IntPredata { it + 1 }
println(a.getInt(10))
成员引用
class Child : Person {
override fun walk() {
println("child walk")
}
override fun speak() {
println("child speak")
}
}
//使用::
val b = Child::walk
b(Child())
//使用lambda
val b1 = { c: Child -> c.speak() }
b1(Child())
函数式api
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val list2 = list.filter { it % 2 == 0 }
val list3 = list.map { Child(it) }
回调
java 味道的回调
interface ClickListener {
fun onClick();
}
class View {
lateinit var listener: ClickListener;
fun setOnClickListener(listener: ClickListener) {
this.listener = listener;
}
fun click() {
listener.onClick()
}
}
val view = View()
view.setOnClickListener(object : ClickListener {
override fun onClick() {
println("onclick")
}
})
view.click()
kotlin 风味
class View2{
lateinit var listener:(Unit)->Unit
fun setOnClickListener2(listener:(Unit)->Unit){
this.listener = listener
}
fun click2(){
listener.invoke(Unit)
}
}
val view2 = View2()
view2.setOnClickListener2 {
println("onclick2")
}
view2.click2()
更纯正的 利用函数式接口
fun interface ClickListener2{
fun onClick2()
}
class View2{
lateinit var listener2:ClickListener2
fun setOnClickListener22(listener2: ClickListener2){
this.listener2 = listener2
}
fun click2(){
listener2.onClick2()
}
}
val view2 = View2()
val listener = ClickListener2{
println("--------")
}
view2.setOnClickListener22(listener)
view2.click2()
class View2 (val id: Int){
lateinit var listener2: ClickListener2
fun setOnClickListener22(listener2: ClickListener2) {
this.listener2 = listener2
}
fun click2() {
listener2.onClick2(this)
}
}
fun interface ClickListener2 {
fun onClick2(view2:View2)
}
val listener = ClickListener2 { view ->
println(view.id)
}
val view2 = View2(123)
view2.setOnClickListener22(listener)
view2.click2()