March kata – FizzBuzz

The March kata was FizzBuzz. This is my third kata done in Scala. For the full source code, go to GitHub.

class FizzyBuzzyInt(i: Int) {
  def isFizzy = divisibleBy(3) || contains(3)
  def isNotFizzy = !isFizzy
  def isBuzzy = divisibleBy(5) || contains(5)
  def isNotBuzzy = !isBuzzy

  private def divisibleBy(divisor: Int) = i % divisor == 0
  private def contains(n: Int) = i.toString contains n.toString
}

class FizzBuzz {
  implicit def extendInt(n: Int) = new FizzyBuzzyInt(n)

  def printSequence(out: PrintStream) = {
    (1 to 100).foreach(n => out.println(sayOnNumber(n)))
  }

  private def sayOnNumber(number: Int): String = {
    number match {
      case n if (n isFizzy) && (n isNotBuzzy) => "Fizz"
      case n if (n isBuzzy) && (n isNotFizzy) => "Buzz"
      case n if (n isFizzy) && (n isBuzzy) => "FizzBuzz"
      case _ => number.toString
    }
  }
}

Like for Roman Numerals I used Scala’s pattern matching. I find it extremely powerful, especially if you have a Java/C++ background. I suppose I’m obeying Maslow’s Law of the instrument (“if all you have is a hammer, everything looks like a nail”). Anyway, this is the purpose of a kata – to play with language capabilities on a safe playground.

To use the hammer ever more, I want to implement fizzy and buzzy predicates using Scala’s case classes and combine them with the pattern matching.

Advertisements