How to invoke passed method which has argument in kotlin?

1.6k views Asked by At

I am trying to invoke a method with argument received as an argument but not able to do so. Here is what I am trying.

I have a method which gets me alert dialog object like below.

fun getAlertDialog(
title: String,
positiveButtonText: String,
positiveClickAction: (() -> Unit)) {
someTextView.setOnClickListener {
positiveClickActin.invoke()
}

and the above can be called like below

val dialog = getAlertDialog("Title", "Ok", ::clickedOk)

considering clickedOk is a void method like below

fun clickedOk() {
println("clicked")
}

But I am stuck when i want to pass a method with argument. Let's say I want to print some variable. The getSimpleDialog method can be changed as below.

fun getAlertDialog(
title: String,
positiveButtonText: String,
positiveClickAction: ((any: Any) -> Unit))
someTextView.setOnClickListener {
positiveClickActin.invoke() //this cannot be achieved now as the method takes an argument
}

and call it as

val dialog = getSimpleDialog("Hello", "ok", { variable -> println("clicked $variable")})

but i cannot invoke this method in the getSimpleDialog's on click listener. How do I achieve it?

1

There are 1 answers

1
stinepike On

You can either call

positiveClickActin.invoke(param)

or simply,

positiveClickActin(param)

Similarly for no parameter case you can use

positiveClickActin()

Instead of calling invoke().

While reading in the doc, the invoke() looks to be useful while having mixed of java and kotlin code. (but I might be wrong here as I am still new in kotlin)