andthen

Fun with Scala functions (andThen and compose)

Here’s a little fun with Scala functions, including the use of andThen and compose:

scala> val add1 = (i: Int) => i + 1
add1: Int => Int = <function1>

scala> val double = (i: Int) => i * 2
double: Int => Int = <function1>

scala> val addThenDouble = add1 andThen double
addThenDouble: Int => Int = <function1>

scala> addThenDouble(1)
res0: Int = 4

scala> val doubleThenAdd = add1 compose double
doubleThenAdd: Int => Int = <function1>

scala> doubleThenAdd(1)
res1: Int = 3

(Inspired by the book, Functional and Reactive Domain Modeling, and my own book, Learning Functional Programming in Scala.)

Simple concurrency with Scala Futures (Futures tutorial)

Table of Contents1 - Problem2 - Solution3 - Run one task, but block4 - Run one thing, but don’t block, use callback5 - The onSuccess and onFailure callback methods6 - Creating a method to return a Future[T]7 - How to use multiple Futures in a for loop8 - Discussion9 - A future and ExecutionContext10 - Callback methods11 - For-comprehensions (combinators: map, flatMap, filter, foreach, recoverWith, fallbackTo, andThen)12 - See Also13 - The Scala Cookbook

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 13.9, “Simple concurrency with Scala Futures.”

Back to top

Problem

You want a simple way to run one or more tasks concurrently in a Scala application, including a way to handle their results when the tasks finish. For instance, you may want to make several web service calls in parallel, and then work with their results after they all return.

Back to top

Solution

A Future gives you a simple way to run an algorithm concurrently. A future starts running concurrently when you create it and returns a result at some point, well, in the future. In Scala, it’s said that a future returns “eventually.”