Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding `andThen`

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.

like image 863
Kevin Meredith Avatar asked Nov 29 '13 19:11

Kevin Meredith


People also ask

What is andThen () in Java?

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.

What is andThen in Scala?

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

What is a composed function Java?

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.


1 Answers

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

like image 111
Lee Avatar answered Oct 18 '22 01:10

Lee