How does the below scala implementation of FizzBuzz work ?
Here is what I think, but im not sure if im on the right track :
The use of => Is this a high order function, if so it is just returning a String
i is a String which contains either "FizzBuzz" , "Fizz" or "Buzz"
package fizzbuzz
object FizzBuzz {
def main(args : Array[String]) {
(1 until 100).map(_ match {
case i : Int if ((i % 3) == 0 && (i % 5) == 0) => "FizzBuzz"
case i : Int if ((i % 3) == 0) => "Fizz"
case i : Int if ((i % 5) == 0) => "Buzz"
case i : Int => i.toString
}).foreach(println _)
}
}
No, the
=>here is part of the match-case syntax. It separates the pattern for the given case from the case’s body, i.e. the syntax iscase pattern => bodywherepatterna pattern to match against the given value andbodyis the code that’s supposed to execute ifpatternmatches.The code works by iterating over the numbers from 1 until 100 (by using map) and matching each number against the patterns in the
matchblock. The patterns use pattern guards to check whether each number is divisible by 3, 5 or both (or neither). The result is a sequence of strings. The code then iterates over that sequence usingforeachand prints each item usingprintln.