dilvan
dilvan

Reputation: 2239

How can I declare a function parameter that can be a string or a function, in Kotlin?

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

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

Answers (2)

anon
anon

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

zsmb13
zsmb13

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

Related Questions