Replace if-else with functional code

functional-programming, pattern-matching, scala

Solution

Using `if-else` is totally acceptable for functional programming, because `if-else` in Scala is merely an expression. The reasons to decide between `if-else` and pattern-matching should be focused on improving readability, mainly.

Here's my try at rewriting your code. I'm actually not using pattern matching here, but a `for`-comprehension to sum the values.

def sumOfValues = for{
  mx <- myMap.get(x)
  my <- myMap.get(y)
} yield mx + my

def valueOfSumIfEven = myMap.get(x+y).filter(_ % 2 == 0) 

sumOfValues orElse valueOfSumIfEven

Problem

I know that in functional style all `if-else` blocks replaced by pattern matching. But how I can handle `Map`s with pattern matching in Scala? For example how I can rewrite this code in more functional style? ``` val myMap= getMap() if(myMap.contains(x) && myMap.contains(y)) Some(myMap(x) + myMap(y)) else if(myMap.contains(x + y)){ val z = myMap(x + y) if (z % 2 == 0) Some(z) else None } else None ```

Original source