Java coders go Scala

“It works this way as well, so what’s the benefit in some functional solution?”

Scala dojoers

Dojo master expaining the rules of bowling.

Functional programming emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state” (Wikipedia). We decided to give it a shot and set up a dojo session with Scala. Let’s kill Java together! Some of us had some experience with Scala, but most were first timers. The dojo challenge was to develop a bowling scorecard calculator. First we really gave an effort to write a functional solution. But after an hour and a half when we had basically nothing ready we started taking shortcuts. “It works this way as well, so what’s the benefit in some functional solution?” Turns out that changing the mindset of 10 proud java coders doesn’t happen in one dojo.

Here you can see our solution. You might notice that the game state is stored in the Round-object:

class ScoreCard {
 val rounds = ListBuffer[Round](new Round, new Round, new Round, new Round, new Round, new Round, new Round, new Round, new Round, new Round)

 def addThrow(score : Int) = {//still ambitiously going for a functional solution
  rounds.find((!_.isFull)).get.addThrow(score)
  this
 }

 def score : Int = {
  var totalscore = 0
  var current = 0
  var lastFirst = 0
  var lastSecond = 0

 for (round <- rounds.reverse) {//this works so what the heck...
  if (round.isStrike) {
   totalscore += round.getScore() + lastFirst
  } else if(round.isSpare){
   totalscore += round.getScore() + lastFirst + lastSecond
  } else {
   totalscore += round.getScore()
  }
  lastSecond = if (round.lastSecond == 0) lastFirst else round.lastSecond
  lastFirst = round.lastFirst

  }
  totalscore
 }
}

class Round {
 val throws = new ListBuffer.empty[Int]()

 def addThrow(score : Int) = throws += score

 def isFull = throws.length == 2 || (throws.length == 1 && throws.head == 10)

 def getScore() : Int = {
  if (throws.length == 0) {
  return 0
 }
  throws.reduceRight(_ + _)
 }

 def isSpare() : Boolean = {
  return throws.length == 2 && getScore() == 10
 }

 def isStrike() : Boolean = {
  return throws.length == 1 && getScore() == 10
 }

 def lastFirst : Int = {
  if (throws.length > 0) return throws.head
  0
 }

 def lastSecond : Int = {
  if (throws.length > 1) return throws(1)
  0
 }
Below is a functional style solution made afterwards by two ambitious Houstonians. Is it based on the actual functions better than the first solution?
class ScoreCard {
 val rounds = List.tabulate(9)(i => new Round) ::: List(new FinalRound())

 def addThrow(score :Int) = { rounds.filter(!_.isFull).head.addThrow(score); this }

 def getRoundScores = {

  // according the the bowling rules, the last (potential) throw is special
  val allThrows = rounds.filter(_.isFull).reverse.flatten(itr => itr.throws.slice(0,2).reverse)

  def countScoresFromRounds(throws: List[Int]): Int = throws match {
   case first :: second :: 10 :: rest =>
   (2 * first) + second + countScoresFromRounds(throws.tail)
   case first :: second :: third :: fourth :: rest if third + fourth == 10 =>
   first + (2 * second) + countScoresFromRounds(third :: fourth :: rest)
   case first :: second :: rest =>
   first + second + countScoresFromRounds(rest)
   case listTail :List[Int] =>
   listTail.foldLeft(0)(_ + _)
  }

  def getLastPotentialThrowValue = {
   rounds.filter(_.isInstanceOf[FinalRound]).headOption match {
    case Some(x) =>
    if (x.throws isDefinedAt(2)) x.throws apply 2
    else 0
    case None => 0
   }
  }

 countScoresFromRounds(allThrows.toList) + getLastPotentialThrowValue
 }
}

class Round {
 val throws = ListBuffer.empty[Int]

 def addThrow(score :Int) = { throws += score; this }

 def isFull = throws.length == 2 || sum == 10

 def sum = throws.foldLeft(0)(_ + _)
}

class FinalRound extends Round {

 override def isFull = throws.length == 3 || (throws.length == 2 && sum < 10)
}

“In which type of solutions could Scala beat Java?”

What’s the benefit in functional programming? In which type of solutions could Scala beat Java? Is it worth the effort for a Java coder to learn Scala? The idea of focusing on the real functions rather than creating artificial states sounds intriguing when solving true business problems! But learning functional thinking takes a lot more than one dojo session.

Thanks for the great dojo once again,

Ohto Rainio

Special thanks to our dojo master Henri Meltaus and Scala pros Heikki Leskinen and Esko Pylsy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s