2023年9月19日 星期二

【Kotlin】 lambda、SAM轉換、first-class function


lambda 結構

來源 : Kotlin 中的集合 (android.com)
(若是參數需要接收但不會用到,可以將其命名為「_」。)

it : 單個參數的隱式名稱


val triple: (Int) -> Int = { it * 3 }

使用範例

來源 : Kotlin Examples: Learn Kotlin Programming By Example (kotlinlang.org)

// All examples create a function object that performs upper-casing.
// So it's a function from String to String

val upperCase1: (String) -> String = { str: String -> str.uppercase() } // 1

val upperCase2: (String) -> String = { str -> str.uppercase() }         // 2

val upperCase3 = { str: String -> str.uppercase() }                     // 3

// val upperCase4 = { str -> str.uppercase() }                          // 4

val upperCase5: (String) -> String = { it.uppercase() }                 // 5

val upperCase6: (String) -> String = String::uppercase                  // 6

println(upperCase1("hello"))
println(upperCase2("hello"))
println(upperCase3("hello"))
println(upperCase5("hello"))
println(upperCase6("hello"))

HELLO
HELLO
HELLO
HELLO
HELLO

SAM轉換功能

僅具有一個抽象方法的介面稱為函數式介面(
functional interface)
單一抽象方法(SAM)介面(
Single Abstract Method (SAM) interface)
函數式介面可以有多個非抽象成員,但只能有一個抽象成員。

 對於只有一個 abstract method 的 interface ,可以不用寫出 override ,使用 lambda 代替。

比如 :

 Functional (SAM) interfaces | Kotlin Documentation (kotlinlang.org)



fun interface IntPredicate {
   fun accept(i: Int): Boolean
}

val isEven = IntPredicate { it % 2 == 0 }

fun main() {
   println("Is 7 even? - ${isEven.accept(7)}")
}
Is 7 even? - false

又如寫 Android 會用到的  :
圖片來源 : Kotlin 中的集合 (android.com)


頭等(一級)函數 first-class function

函數可作為別的涮的參數、返回值、賦值給變數或存在資料結構中。
Kotlin 中的函數都是 first-class function 。

lambda vs 匿名函數 (待補充)

匿名函數 :
  • 參數需要在括號內傳遞
lambda :
  • 若函數的最後一個參數是函數,而要傳入的參數是 lambda,則可以將其放在括弧之外(稱:拖尾 lambda 表達式)。

資料來源

0 comments:

張貼留言