scala 理解`andThen`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20292439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding `andThen`
提问by Kevin Meredith
I encountered andThen, but did not properly understand it.
我遇到过andThen,但没有正确理解它。
To look at it further, I read the Function1.andThendocs
为了进一步研究,我阅读了Function1.andThen文档
def andThen[A](g: (R) ? A): (T1) ? A
mmis a MultiMapinstance.
mm是一个MultiMap实例。
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 andThenpowerful? Based on this example, it looks like mm.andThende-sugars to x => mm.apply(x). If there is a deeper meaning of andThen, then I haven't understood it yet.
很andThen厉害吗?基于这个例子,它看起来像是mm.andThen去糖x => mm.apply(x)。如果有更深层的含义andThen,那我还没有理解。
回答by Lee
andThenis just function composition. Given a function f
andThen只是函数组合。给定一个函数f
val f: String => Int = s => s.length
andThencreates a new function which applies ffollowed by the argument function
andThen创建一个新函数,f该函数后跟参数函数
val g: Int => Int = i => i * 2
val h = f.andThen(g)
h(x)is then g(f(x))
h(x)然后是 g(f(x))

