【问题标题】:How to pass a function as parameter in kotlin - Android如何在 kotlin 中将函数作为参数传递 - Android
【发布时间】:2018-07-06 08:37:43
【问题描述】:

如何使用 Kotlin 在 android 中传递函数。如果我知道这样的功能,我可以通过:

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

我想传递任何函数,例如 ->
fun passAnyFunc(fun : (?) ->Unit){}

【问题讨论】:

  • 当您说“任何功能”时,您真的是指“可能存在的每一个功能”吗?或者只是“任何接受某种类型的参数并返回Unit的函数”?
  • 将任何类型的函数作为函数的参数传递?你现在明白了吗
  • 那是不可能的。这听起来像是一个 XY 问题。你打算用传入的函数(可以接受任意数量的参数并返回任何类型)做什么?
  • 嗨@Sweeper 下面是答案。

标签: android function parameters kotlin


【解决方案1】:

您可以使用匿名函数或 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")
    }

}

【讨论】:

  • 谢谢Yaswant Narayan。这只是我所期待的
  • 你也可以像something(true) { prinln("bleh") }这样传递lambda
  • 怎么样?我没找到你
  • something() 接受两个参数。一个是布尔值,另一个是函数本身。所以something()变成了高阶函数。对于第二个参数,我们传递了一个叫做 lambda 的东西,它只是一个用{ ... } 括起来的函数体。由于something() 接受一个函数作为它的最后一个参数(大多数高阶函数都这样做),我们可以像我之前的帖子一样在函数调用之外传递 lambda。
【解决方案2】:

方法作为参数示例:

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)
}

【讨论】:

    【解决方案3】:

    使用接口:

    interface YourInterface {
        fun functionToCall(param: String)
    }
    
    fun yourFunction(delegate: YourInterface) {
      delegate.functionToCall("Hello")
    }
    
    yourFunction(object : YourInterface {
      override fun functionToCall(param: String) {
        // param = hello
      }
    })
    

    【讨论】:

    • 我可以传递任何我想要通用方法的接口,所以为此我需要为不同的方法创建不同的接口。
    【解决方案4】:

    首先在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2015-01-23
      • 2013-04-13
      • 2017-05-29
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多