A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.

This article is part of the series "Scala Tutorial Through Katas". Articles are divided into easy, medium and hard. Beginners should start with easy ones and move towards more complicated once they feel more comfortable programming in Scala.

For the complete list of Scala katas and solutions please visit the index page



The article assumes that the reader is familiar with the basic usage of ScalaTest and knows how to run them from his favorite Scala IDE (ours is IntelliJ IDEA with the Scala plugin).

Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to write the implementation for the first test, confirm that it passes and move to the next. Once all of the tests pass, the kata can be considered solved.

One possible solution is provided below the tests. Try to solve the kata by yourself first.

Fizz Buzz Kata

Return "fizz", "buzz" or "fizzbuzz".

For a given natural number greater than zero return:

"fizz" if the number is dividable by 3

"buzz" if the number is dividable by 5

"fizzbuzz" if the number is dividable by 15

the same number if no other requirement is fulfilled

[TESTS]

class FizzBuzzTest extends UnitSpec { "FizzBuzz" should "return fizz if the number is dividable by 3" in { FizzBuzz.getResult(3) should be ("fizz") FizzBuzz.getResult(6) should be ("fizz") } it should "return buzz if the number is dividable by 5" in { FizzBuzz.getResult(5) should be ("buzz") FizzBuzz.getResult(10) should be ("buzz") } it should "return fizzbuzz if the number is dividable by 15" in { FizzBuzz.getResult(15) should be ("fizzbuzz") FizzBuzz.getResult(30) should be ("fizzbuzz") } it should "return the same number if no other requirement is fulfilled" in { FizzBuzz.getResult(1) should be ("1") FizzBuzz.getResult(2) should be ("2") FizzBuzz.getResult(4) should be ("4") } }

Test code can be found in the GitHub FizzBuzz.scala.

[ONE POSSIBLE SOLUTION]

object FizzBuzz { def getResult(number: Int) = { var result = "" if (number % 3 == 0) result = "fizz" if (number % 5 == 0) result += "buzz" if (result == "") number.toString else result } }

Better solution was provided by rayyildiz.

[BETTER POSSIBLE SOLUTION]

object FizzBuzz { def getResult(number: Int): String = (number % 3, number % 5) match { case (0 , 0) => "fizzbuzz" case (0 , _) => "fizz" case (_ , 0) => "buzz" case _ => number.toString() } }

The solution code can be found in FizzBuzz.scala solution or in rayyildiz's repository.

What was your solution? Post it as a comment so that we can compare different ways to solve this kata.