As the title suggests, this is my FizzBuzz implementation in Scala.

I started learning Scala (and functional programming in general) in small steps about two months ago, and one recent assignment was the FizzBuzz task. Here is the simple code I came up with to solve the problem. It runs perfectly, but I figured CodeReview would be able to easily point out thinks I'm missing.

I do think that the hardcoded magic values (3,5,15,"Fizz","Buzz","FizzBuzz") are slightly problematic, but I'm not sure if that's general consensus or what the best way to handle that is.


package fizzbuzz

object FizzBuzz {

  def fizzbuzz(i: Int): String = i match {
    case i if i % 15 == 0 => "FizzBuzz" //because i | 15 is the same as i | 5 and i | 3
    case i if i % 5 == 0 => "Buzz"
    case i if i % 3 == 0 => "Fizz"
    case i => i toString

  def fizzbuzz(start: Int, end: Int): List[String] = (start to end map fizzbuzz) toList

  //assignment requirement: return list of first 100 fizzbuzzed numbers
  def fizzbuzz100(): List[String] = fizzbuzz(1,100)

Main.scala (sample usage of FizzBuzz object)

package fizzbuzz

object main {
  def main(args: Array[String]): Unit = {
     FizzBuzz.fizzbuzz100() map println

1 Answer 1


Although Rosetta Code doesn't always provide the most idiomatic code for each language, look at the "idiomatic solution":

object FizzBuzz extends App {
  1 to 100 foreach { n =>
    println((n % 3, n % 5) match {
      case (0, 0) => "FizzBuzz"
      case (0, _) => "Fizz"
      case (_, 0) => "Buzz"
      case _ => n

Your code doesn't use pattern matching well (it is kind of unecesary the way you use it). I would advise you take the solution you have and rewrite it to use pattern matching more like the Rosetta Code solution.

  • \$\begingroup\$ Thanks for the pattern matching tip; I was looking for a better way to use it and this is it. \$\endgroup\$ Commented Nov 17, 2016 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.