Is it possible to run a function from a hash map?

Viewed 37

How do I run a function from a hashmap. In this case I'm trying to run the Info.sendInfo function.

abstract class Listener: ListenerAdapter() {
        fun checkCommand(args: List<String>, event: MessageReceivedEvent) {
            val map: Map<String, Unit> = mapOf(
                "!info" to Info.sendInfo(event)
            )
            
            map[args[0]].runFunction
        }
    }
1 Answers

If you want to store functions as values in your map, your value type of the map needs to be a definition for that function, not Unit. And when you define the entries of your map, you need to use a function reference which involves either using :: or a lambda to define the function. What you're doing right now is immediately calling the function at the time the map is created and storing the return value in your map.

For this case, the function type is a function that takes a MessageReceivedEvent as a parameter and returns Unit, which is a (MessageReceivedEvent)->Unit function, so your code to define the map should look like:

val map: Map<String, (MessageReceivedEvent)->Unit> = mapOf(
    "!info" to Info::sendInfo
)

Then to call the function, you use parentheses like with any other function call. However, maps return nullable values when you use the [] accessor because it's possible they don't have a value for the key you're supplying. So you should either use the getValue() function instead of [], which asserts that you know the value is in the map (otherwise it throws an exception), or you can use a null-safe invoke call.

// Value asserted, exception thrown if you're wrong
map.getValue(args[0])(event)

// Null safe call
map[args[0]]?.invoke(event)
Related