繁体   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