簡體   English   中英

如何在 kotlin 中將函數作為參數傳遞 - Android

[英]How to pass a function as parameter in kotlin - Android

如何使用 Kotlin 在 android 中傳遞函數。 如果我知道這樣的功能,我可以通過:

fun a(b :() -> Unit){
}
fun b(){
}

我想傳遞任何函數,例如 ->
fun passAnyFunc(fun : (?) ->Unit){}

您可以使用匿名函數或 lambda 如下

fun main(args: Array<String>) {

    fun something(exec: Boolean, func: () -> Unit) {
        if(exec) {
            func()
        }
    }

    //Anonymous function
    something(true, fun() {
        println("bleh")
    })

    //Lambda
    something(true) {
        println("bleh")
    }

}

方法作為參數示例:

fun main(args: Array<String>) {
    // Here passing 2 value of first parameter but second parameter
    // We are not passing any value here , just body is here
    calculation("value of two number is : ", { a, b ->  a * b} );
}

// In the implementation we will received two parameter
// 1. message  - message 
// 2. lamda method which holding two parameter a and b
fun calculation(message: String, method_as_param: (a:Int, b:Int) -> Int) {
     // Here we get method as parameter and require 2 params and add value
     // to this two parameter which calculate and return expected value
     val result = method_as_param(10, 10);

     // print and see the result.
     println(message + result)
}

使用接口:

interface YourInterface {
    fun functionToCall(param: String)
}

fun yourFunction(delegate: YourInterface) {
  delegate.functionToCall("Hello")
}

yourFunction(object : YourInterface {
  override fun functionToCall(param: String) {
    // param = hello
  }
})

首先在 Oncreate 中聲明一個 lambda 函數(一個沒有名字的函數被稱為 lamdda 函數。它來自 kotlin 標准庫而不是 kotlin 語言,它帶有 {} ),如下所示

 var lambda={a:Int,b:Int->a+b}

現在創建一個接受另一個函數作為參數的函數,如下所示

fun Addition(c:Int, lambda:(Int, Int)-> Int){
    var result = c+lambda(10,25)
    println(result)

}

現在通過將 lambda 作為參數傳遞給 onCreate 中的 Addition 函數,如下所示

Addition(10,lambda)//  output 45

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM