Friday, 13 January 2012

Callback a la scala

The first (and not only) un-natural element when moving from Java to Scala is that callback via interfaces and anonymous classes are not needed anymore. Let's walk through a simple example, using the Spring-like SQL template First in Java:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

interface ICallbackHandler {
  void process(ResultSet rs);
}

final class JSqlTemplate {
  DataSource ds = null;
 
  public void query(final String sql, final ICallbackHandler cb) throws Exception {
    final Connection conn = ds.getConnection();
    final Statement stmt = conn.createStatement();
    final ResultSet rs = stmt.executeQuery(sql);
    while(rs.next()) cb.process(rs);
      rs.close();
      stmt.close();
      conn.close();
    }
}

public class DBCallbackTest {
  public static void main(String[] args) throws Exception {
    new JSqlTemplate().query("select * from whatever", new ICallbackHandler() {
      public void process(ResultSet rs) {
        // get stuff here
      }
    });
  }
}
In Scala, there is no need to define a ICallbackHandler .. you can just go for:
import javax.sql.DataSource
import java.sql.ResultSet

sealed class SSqlTemplate(dataSource: DataSource)  {
  def query(sql: String, rowHandler: (ResultSet) => Unit) = {
    val conn = dataSource.getConnection
    val stmt = conn.createStatement
    val rs = stmt.executeQuery(sql)
    while (rs.next) rowHandler(rs)
    rs.close
    stmt.close
    conn.close
  }
}

object SDbCallback {
  def main(args: Array[String]): Unit = {
    val ds:DataSource = null
    new SSqlTemplate(ds).query("select * from whatever",
        {(rs: ResultSet) =>
          // get stuff here
       })
  }
}

No comments:

Blog Archive