How to call function indirectly in Kotlin

85 views Asked by At

Assume I have a mutableMap:

val MM = mutableMapOf()

Now I define a function as a method for it:

MM["testF"] = fun () {
  println("WOW")
}

Now I want to call it in another place:

val MMTF = MM["testF"] as Function<*>
MMTF() <-- NOT WORKING

Any help will be appreciated.

1

There are 1 answers

0
AlexandreLadeira On

This code will print bar

fun main() {
    val map = mutableMapOf<String, () -> Any>()
    map["foo"] = {
        println("bar")
    }
    run(map["foo"]!!)
}