Functional Programming: Higher-order functions

Higher-order functions have functions as parameters or as return types. In Java before v8 every value is a primitive type or object. In Scala everything is an object, even functions, so functions can be passed as arguments. In Java they would need to be wrapped in a class.

An example:

Here is the Java version, note use of the UnitOfWork interface to chaperone the method doWork().

class TransactionManager {

  public void startTransaction(){ … }
  public void endTransaction() { … }
  public void doInTransaction(final UnitOfWork uow) {
    startTransaction();
    uow.doWork();
    endTransaction();
  }
}

interface UnitOfWork {
  void doWork();
}

class SaveCustomer implements UnitOfWork {
  @Override
  public void doWork() {
    System.out.println("Saving a customer"); 
  }  
}

class Job {
  public void saveCustomerInTransaction() {
      final UnitOfWork u = new SaveCustomer();
      new TransactionManager().doInTransaction(u);
  }
}

Here is the Scala version, we just  assign the function to a value and pass it:

class TransactionManager {
 
  def startTransaction() { … }
  def endTransaction(){ … }

  // This function takes a function ‘doWork’ and executes it. 
  def doInTransaction(doWork: Unit => Unit) {
    startTransaction()
    doWork()
    endTransaction()
  }
}

class Job {
  // Assign a function to a val(ue).
  val saveCustomerFunction = (u: Unit) => { println("Saving a customer") }
  def saveCustomerInTransaction {
    new TransactionManager().doInTransaction(saveCustomerFunction)
  }
}

Scala can be terser than the example above but I have tried to make it easier for a Java developer to read.

Advertisements

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