如何在 Kotlin 中声明可以是字符串或函数的函数参数?
How can I declare a function parameter that can be a string or a function, in 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") }
在下面的函数中,我想将 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") }