Tuesday, October 9, 2007

Applying scala to solving real world problems

Scala is no doubt an excellent language. However, problems like 8-queen or quick sort in the scala doc just aren't  convincing to software professionals in the industry. So I'd like to show how to apply it to solving real world problems in Java. Here let's consider the logging problem in Java. Usually people write code like:

        if (log.isDebugEnabled())
            log.debug("Foo is: " + foo);

Why check isDebugEnabled() if the log object will not log the message if debug is not enabled? This is for performance. If we didn't have this check, the toString() would always be called on foo and the result would always be appended to "Foo is:" to form a new string, even when debug was not enabled.

Scala can easily solve this problem using called-by-name parameters:

class Log {
  var isDebugEnabled: Boolean = false;
  def debug(msg: => String) {  //msg is a string expression that is unevaluated
    if (isDebugEnabled) {
      System.out.println(msg); //evaluate msg as if it is a function

Now you call this method and provide an expression and it won't be evaluated unless debug is enabled:

    val log: Log = new Log();
    var foo: Int = 123;
    log.debug("Foo is:"+foo); //won't be evaluated
    log.isDebugEnabled = true;
    log.debug("Foo is:"+foo); //will be evaluated inside the debug() method