Mark Needham

Thoughts on Software Development

Scala: An attempt to eradicate the if

with 3 comments

In a previous post I included a code sample where we were formatting a page range differently depending on whether the start page and end pages were the same.

The code looked like this:

trait PageAware {
  def startPage:String
  def endPage:String
  def pageRange = if(firstPage == lastPage) "page %s".format(firstPage) else "pages %s-%s".format(firstPage, lastPage)
}

Looking at the if statement on the last line we were curious whether it would be possible to get rid of it and replace it with something else.

In Java we could use the ternary operator:

public class PageAware {
  public String pageRange() {
    return (firstPage == lastPage) ? String.format("page %s", firstPage) : String.format("pages %s-%s", firstPage, lastPage)
  }
}

The if/else statement in Scala is supposed to replace that as far as I understand but I think the ternary operator looks neater.

Beyond defining that we played around with some potential alternatives.

We could use a Map to store the true and false values as keys:

trait PageAware {
  def pageRange = Map(true -> "page %s", false -> "pages %s-%s")(firstPage == lastPage).format(firstPage, lastPage)
}

Uday came up with a pattern matching solution which looks like this:

trait PageAware {
  def pageRange = ((firstPage, lastPage) match { case (`firstPage`, `firstPage`) => "page %s" case _ => "pages %s-%s"}).format(firstPage, lastPage)
}

Unfortunately both of these solutions are significantly less readable than the if/else one so it seems like this is one of the situations where it doesn’t actually make sense to get rid of it.

Be Sociable, Share!

Written by Mark Needham

July 12th, 2011 at 10:50 pm

Posted in Scala

Tagged with

  • Lachlan O’Dea

    Scala is so awesome, you can just write your own ternary operator: http://dibblego.wordpress.com/2008/10/13/does-scala-have-javas-ternary-operator/

  • Kenbot

    I can’ t imagine there’s a great deal of gain in playing code golf with “if (a) b else c”.  Often though, this would be written with a line break before “else”, and the else indented to be immediately below the if.  No need to complicate things just because we can.

  • http://www.markhneedham.com/blog Mark Needham

    @ef6493f5da4d5ec0277b4aa125ad1651:disqus yeh you’re right for these ones we won’t be bothering with any more code golf on if/else!
    We have found some cases when instead of using an if we’ve found ways to just solve the problem using a higher order collection function.It’s the same in any language with those types of functions though, not specific to Scala.