Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application does not take parameters

Tags:

scala

For those scala experts out there I am currently writing code for my university coursework and the compiler has thrown an error whereby I am not sure how to resolve.

The following code should simply invoke a menu option:

 def menu(option: Int): Boolean = {
   actionMap.get(option) match {
    case Some(f) => f()
     case None =>
      println("ERROR: Please enter an option between 1-8")
      true
   }
}

The compiler does not like this line:

case Some(f) => f()

and more specifically it does not like

=> f()

I am completely new to functional programming and scala therefore, any tips or clue would be awesome.

Thanks

like image 660
Patrick Lafferty Avatar asked Oct 30 '22 16:10

Patrick Lafferty


1 Answers

As actionMap is of type Map[Int, Boolean]. Following code works.

def menu(option: Int): Boolean = {
   actionMap.get(option) match {
    case Some(value) => value 
     case None =>
      println("ERROR: Please enter an option between 1-8")
      true
   }
}

Parenthesis is for function application. So f() should be used only if f is a function.

actionMap.get(someIntValue) will return option of Boolean and you can pattern match on the option to extract the boolean value. In your code snippet, you are trying to apply the boolean value which is not allowed as it is not a function but a value.

For example if you actionMap were to be something like below then you earlier code is valid

val actionMap = Map(1 -> { () -> true}, 2 -> { () -> false})

def menu(option: Int): Boolean = {
   actionMap.get(option) match {
    case Some(f) => f() //now f() is valid.
     case None =>
      println("ERROR: Please enter an option between 1-8")
      true
   }
}
like image 191
pamu Avatar answered Nov 11 '22 15:11

pamu