3

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
dilvan
  • 2,109
  • 2
  • 20
  • 32

2 Answers2

6

You could just overload the function:

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

fun test(attr: String, createValue: () -> String): Unit {
    // do stuff
}
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Isn't there a way to create a variable for both types? Like `var x:dynamic` where `x` can be a string or a function? `x="foo"; x= {print (...)}` – dilvan Oct 12 '17 at 10:33
2

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") }