Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala How To Use Map To Store Methods as values

Tags:

scala

I have to present a number of options to the user such as:

1. Option 1
2. Option 2
Please choose your option:

In my scala code, each of the options has its own method associated with it. For example:

def method1(){
 println("method1")
}

def method2(){
 println("method2")
}

Instead of using a switch statement, I would like to use a map structure like this:

val option= Console.readInt
val options= Map(1 -> method1, 2-> method2 )

Then I want to call the corresponding method by invoking:

options.get(option).get

However, when it reaches the line val options= Map(1 -> method1, 2-> method2 ), it prints the following:

method1
method2

Can you please show me directions to accomplish this?

Thanks,

like image 999
TrongBang Avatar asked Mar 18 '23 20:03

TrongBang


1 Answers

Your methods, which have an argument type of (), can be called with or without the parentheses. Just writing the name of the method is parsed as a method call. To get a function as a value that will call your method, you can write an anonymous function with a _ as a placeholder for the () argument:

method1 _

In your example, this would then be

val options = Map(1 -> method1 _, 2 -> method2 _)
options.get(option).get()

The parentheses are necessary here. They aren't for the method get like it might seem. They're applied to the function object returned by get.

Also note that you can replace map.get(key).get with the equivalent code map(key):

options(option)()

As pointed out by @tuxdna, your code will throw an exception if option is not one of the keys in the options map. One way to avoid that is to do a match on the result of options.get():

options.get(option) match {
   case Some(f) => f()
   case None => // invalid option selected
}
like image 138
Dan Getz Avatar answered Mar 21 '23 02:03

Dan Getz