Yes, there is a way how to execute object methods inside a Map. But you first have to put functions into the map. What you did, was putting results of object methods into your map. So your methods were executed and their results were put as values into the map.
Let's assume, that your methods are defined in this class:
class SomeObject {
def doStuff(): String = "I did stuff"
def doThing(): String = "I did a thing"
}
And you have an instance of the class:
val someObject = new SomeObject
First way, how to delay execution of these methods is to create new function using lambdas and execute methods inside these lambdas:
val actions = Map(
"foo" -> (() => someObject.doStuff()),
"bar" -> (() => someObject.doThing()),
)
You can use special syntax to convert object methods directly into lambdas:
val actions = Map(
"foo" -> someObject.doStuff _,
"bar" -> someObject.doThing _
)
If you specify type of the map explicitly, than you can get rid of the underscore too:
val actions: Map[String, () => String] = Map(
"foo" -> someObject.doStuff,
"bar" -> someObject.doThing
)
Next, you need to get the function from the map. If there is no function for the key, than use a default function - one, that always returns None
val action = actions.getOrElse(input, () => None)
And finally, you invoke the action:
action()