Patrick Lafferty
Patrick Lafferty

Reputation: 537

Application does not take parameters

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

Upvotes: 5

Views: 6344

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

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
   }
}

Upvotes: 2

Related Questions