Functional Programming: Higher-order functions

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 (e.g. boolean, char, int etc.) or object (String, List, etc.). In Scala a value can be a function, meaning it has properties and can be passed to and returned from other functions.

In practice this means that, where a class might be generated to ‘chaperone’ a function in java, just the method can be passed.

I will give an example:

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

class TransactionManager {
  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 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