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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With