天天看點

Kotlin的Lambda表達式

一、什麼是Lambda表達式

就是匿名函數

寫法:{[參數清單] -> [函數體,最後一行是傳回值]}

**舉例:**val sum = {a: Int, b: Int -> a+b}

二、Lambda 的類型

()-> Unit

無參,傳回值為Unit

(Int) -> Int

傳人整型,傳回一個整型

(String,(String) -> String)->Boolean

傳入字元串、Lambda表達式,傳回Boolean

三、Lambda表達式的調用

用()調用

等價于invoke()

舉例:

定義一個:val sum = {a: Int,b: Int -> a+b}

調用一下:sum(2,3)

sum.invoke(2,3)

四、首先來寫一個例子

//Lambda表達式,傳人兩個(Int,Int)-> Int
 val sum = {arg1: Int, arg2: Int ->
    //println("$arg1 + $arg2 = ${arg1 + arg2}")
    arg1 + arg2
}           

五、找到kotlin的Functions源碼

因為是從0開始的,可以看到最多參數隻能有23個

package kotlin.jvm.functions

/** A function that takes 0 arguments. */
public interface Function0<out R> : Function<R> {
    /** Invokes the function. */
    public operator fun invoke(): R
}
/** A function that takes 1 argument. */
public interface Function1<in P1, out R> : Function<R> {
    /** Invokes the function with the specified argument. */
    public operator fun invoke(p1: P1): R
}
/** A function that takes 2 arguments. */
public interface Function2<in P1, in P2, out R> : Function<R> {
    /** Invokes the function with the specified arguments. */
    public operator fun invoke(p1: P1, p2: P2): R
}
......
/** A function that takes 21 arguments. */
public interface Function21<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, in P20, in P21, out R> : Function<R> {
    /** Invokes the function with the specified arguments. */
    public operator fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19, p20: P20, p21: P21): R
}
/** A function that takes 22 arguments. */
public interface Function22<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, in P20, in P21, in P22, out R> : Function<R> {
    /** Invokes the function with the specified arguments. */
    public operator fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19, p20: P20, p21: P21, p22: P22): R
}           

六、源碼位置

繼續閱讀