Understanding `andThen`

泪湿孤枕 提交于 2019-12-03 08:42:31

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/20292439/understanding-andthen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!