28

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

38

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))

Lee
  • 142,018
  • 20
  • 234
  • 287
  • 4
    wheres the benefit over writing : g(f(x)) ? – Stefan Kunze Nov 29 '13 at 20:02
  • 4
    @StefanKunze Maybe because it's easier to write `val h = first andThen second andThen third andThen fourth` than, for example, `val h : String => Int = x => fourth(third(second(first(x))))` :) Fun fact: F# has `>>` operator for left-to-right function composition, so you can also save a few keystrokes. – Patryk Ćwiek Nov 29 '13 at 20:07
  • 14
    There is _no_ advantage to writing `f.andThen(g)(x)` over `g(f(x))`. But there _is_ an advantage to writing `h(f andThen g)` over having to write another function `def fAndThenG(x:String) = f(g(x))` so that you can call `h(fAndThenG)`. That is, if you want to pass the composed function as an argument, `andThen` allows you to do so quickly and anonymously. – AmigoNico Nov 30 '13 at 00:41
  • 4
    why did you use `val` over `def` for functions `f` and `g`? – Kevin Meredith Nov 30 '13 at 22:38
  • @StefanKunze It isn't syntactic sugar at all. It's a function. Syntactic sugar is *syntax* that is there to do something that other syntax could do. Functions are concrete implementations, not syntax. Scala has no syntax for function composition (just function application). – itsbruce Jun 26 '18 at 13:29
  • The way that I like to reason about function composition is that it's like a Unix pipe. You're just evaluating a function of a function, f(g(x)), or f.g (x), which ties very closely to how Unix processes output text to streams, then taken as the input of another process, and so on and forth. – Alfredo Gallegos Sep 28 '18 at 18:41