Skand kumar
Skand kumar

Reputation: 93

How to pass a function as parameter in kotlin - Android

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

Upvotes: 6

Views: 14724

Answers (4)

Paramatma Sharan
Paramatma Sharan

Reputation: 445

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

Upvotes: 1

Farid Haq
Farid Haq

Reputation: 4191

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

Upvotes: 7

Yaswant Narayan
Yaswant Narayan

Reputation: 1342

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

}

Upvotes: 22

Prexx
Prexx

Reputation: 2979

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

Upvotes: 3

Related Questions