首页 > 解决方案 > 如何调用在kotlin中有参数的传递方法?

问题描述

我正在尝试使用作为参数接收的参数调用方法,但无法这样做。这是我正在尝试的。

我有一个方法可以让我得到如下所示的警报对话框对象。

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

上面可以像下面这样调用

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

考虑 clickedOk 是一个 void 方法,如下所示

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

但是当我想传递一个带参数的方法时,我被卡住了。假设我想打印一些变量。getSimpleDialog 方法可以更改如下。

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
}

并将其称为

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

但我无法在 getSimpleDialog 的点击监听器中调用此方法。我如何实现它?

标签: androidkotlin

解决方案


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)


推荐阅读