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.
Java's . compose() and . andThen() are just the Java equivalent of this. Use the one that makes the code seem easiest to you. In terms of performance there is no significant difference.
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))
Functional composition refers to a technique where multiple functions are combined together to a single function. We can combine lambda expression together. Java provides inbuilt support using Predicate and Function classes.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With