Understanding `andThen`

Kevin Meredith picture Kevin Meredith · Nov 29, 2013 · Viewed 14.9k times · Source

I encountered andThen, but did not properly understand it.

To look at it further, I read the Function1.andThen docs

def andThen[A](g: (R) ⇒ A): (T1) ⇒ A

mm is a MultiMap instance.

scala> mm
res29: scala.collection.mutable.HashMap[Int,scala.collection.mutable.Set[String]] with scala.collection.mutable.MultiMap[Int,String] = 
                    Map(2 -> Set(b) , 1 -> Set(c, a))

scala> mm.keys.toList.sortWith(_ < _).map(mm.andThen(_.toList))
res26: List[List[String]] = List(List(c, a), List(b))

scala> mm.keys.toList.sortWith(_ < _).map(x => mm.apply(x).toList)
res27: List[List[String]] = List(List(c, a), List(b))

Note - code from DSLs in Action

Is andThen powerful? Based on this example, it looks like mm.andThen de-sugars to x => mm.apply(x). If there is a deeper meaning of andThen, then I haven’t understood it yet.

Answer

Lee picture Lee · Nov 29, 2013

andThen is just function composition. Given a function f

val f: String => Int = s => s.length

andThen creates a new function which applies f followed by the argument function

val g: Int => Int = i => i * 2

val h = f.andThen(g)

h(x) is then g(f(x))