我如何在Kotlin中声明一个可以是字符串或函数的函数参数?
在下面的函数中,我想传递一个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
类型?
你可以重载这个函数:
fun test(attr: String, value: String) = test(attr, { value }) fun test(attr: String, createValue: () -> String): Unit { // do stuff }
你可以写:
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") }