FizzBuzz is kind of a difficult example because its simplicity means it looks more or less the same in every language. That said, we can go out of our way to emphasize the functional aspect of Scala.
First, we can wrap the core logic of FizzBuzz up in its own function:
def fizzBuzz(x:Int) = {
if (x % 15 == 0)
"FizzBuzz"
else if (x % 3 == 0)
"Fizz"
else if (x % 5 == 0)
"Buzz"
else
x
}
Now, we can compose this with printing and map it over the domain we're interested in:
(1 until 100).map(fizzBuzz _ andThen println)
Notice that, where in Java we would probably repeat the println
in every case, in Scala, with first-class functions, we can easily separate it out as its own step in the process.
The advantage of this becomes clearer when we think about recombining elements. If we wanted to, we could, for example, join everything in a string without rewriting the essential FizzBuzzzing logic:
println((1 until 100).map(fizzBuzz).mkString(", "))
So, hopefully you can see that Scala's "better way" is first-class functions. With them, we more easily compose the pieces of our system.