如何在Kotlin中声明一个可以是字符串或函数的函数参数?

时间:2017-10-11 18:23:40

标签: dynamic types kotlin kotlin-interop

在以下函数中,我想传递一个html标记的属性。这些属性可以是字符串(test("id", "123"))或函数(test("onclick", {_ -> window.alert("Hi!")})):

fun test(attr:String, value:dynamic):Unit {...}

我尝试将参数value声明为Any,即Kotlin中的根类型。但功能不属于Any类型。将类型声明为dynamic,但

  • dynamic不属于某种类型。它只是关闭键入检查参数。
  • dynamic仅适用于kotlin-js(Javascript)。

如何在Kotlin(Java)中编写此函数?函数类型如何与Any相关?是否存在包含函数类型和Any的类型?

2 个答案:

答案 0 :(得分:6)

你可以重载函数:

fun test(attr: String, value: String) = test(attr, { value })

fun test(attr: String, createValue: () -> String): Unit {
    // do stuff
}

答案 1 :(得分:2)

你可以写:

fun test(attr: String, string: String? = null, lambda: (() -> Unit)? = null) {
  if(string != null) { // do stuff with string }
  if(lambda != null) { // do stuff with lambda }
  // ...
}

然后通过以下方式调用该函数:

test("attr")
test("attr", "hello")
test("attr", lambda = { println("hello") })
test("attr") { println("hello") }
test("attr", "hello", { println("hello") })
test("attr", "hello") { println("hello") }
相关问题