Scala How to use a map to store methods as values

I have to present the user with several options, for example:

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

      

In my scala code, each of the parameters 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 the map structure like this:

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

      

Then I want to call the appropriate method by calling:

options.get(option).get

      

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

method1
method2

      

Could you show me how to do this?

Thank,

+3


source to share


1 answer


Your methods that have an argument type ()

can be called with or without parentheses. Simply writing the method name is parsed as a method call. To get a function as a value that your method will call, you can write an anonymous function with _

as a placeholder for the argument ()

:

method1 _

      

In your example it would be

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

      

Parentheses are needed here. They are not for the method get

, as it might seem. They apply to the function object returned get

.



Also note that you can replace map.get(key).get

with an equivalent code map(key)

:

options(option)()

      

As @tuxdna pointed out, your code throws an exception if option

it is not one of the keys in the map options

. One way to avoid this is to do match

as a result options.get()

:

options.get(option) match {
   case Some(f) => f()
   case None => // invalid option selected
}

      

+6


source







All Articles