How to pass a function as parameter in kotlin - Android

强颜欢笑 提交于 2020-12-03 09:46:48

问题


How to pass a function in android using Kotlin . I can able to pass if i know the function like :

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

I want to pass any function like ->
fun passAnyFunc(fun : (?) ->Unit){}


回答1:


Method as parameter Example:

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



回答2:


You can use anonymous function or a lambda as follows

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

}



回答3:


Use an interface:

interface YourInterface {
    fun functionToCall(param: String)
}

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

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



回答4:


First declare a lambda function(a function without name is known as lamdda function. its comes from kotlin standard lib not kotlin langauage which strat with {} ) in Oncreate like below

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

Now Create a function which accept another function as a parameter like below

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

}

Now Call Addition function in onCreate by passing lambda as parameter like below

Addition(10,lambda)//  output 45


来源:https://stackoverflow.com/questions/51206233/how-to-pass-a-function-as-parameter-in-kotlin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!