Reputation: 2239
In the following function, I want to pass to it attributes for a html tag. These attributes can be strings (test("id", "123")
) or functions (test("onclick", {_ -> window.alert("Hi!")})
):
fun test(attr:String, value:dynamic):Unit {...}
I tried to declare the parameter value
as Any
, the root type in Kotlin. But functions aren't of type Any
. Declaring the type as dynamic
worked, but
dynamic
isn't a type. It just turns off typing checking for the parameter.dynamic
only works for kotlin-js (Javascript).How can I write this function in Kotlin (Java)? How do function types relate to Any? Is there a type that includes both function types and Any
?
Upvotes: 3
Views: 124
Reputation:
You could write:
fun test(attr: String, string: String? = null, lambda: (() -> Unit)? = null) {
if(string != null) { // do stuff with string }
if(lambda != null) { // do stuff with lambda }
// ...
}
And then call the function in the following ways:
test("attr")
test("attr", "hello")
test("attr", lambda = { println("hello") })
test("attr") { println("hello") }
test("attr", "hello", { println("hello") })
test("attr", "hello") { println("hello") }
Upvotes: 2
Reputation: 89548
You could just overload the function:
fun test(attr: String, value: String) = test(attr, { value })
fun test(attr: String, createValue: () -> String): Unit {
// do stuff
}
Upvotes: 6