25

我遇到过andThen,但没有正确理解。

为了进一步了解它,我阅读了Function1.andThen文档

def andThen[A](g: (R) ⇒ A): (T1) ⇒ A

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

注意 - 来自DSL 的代码在行动中

andThen强大吗?根据这个例子,它看起来像是mm.andThenx => mm.apply(x). 如果还有更深层次的含义andThen,那我还没有理解。

4

1 回答 1

34

andThen只是功能组合。给定一个函数f

val f: String => Int = s => s.length

andThen创建一个新函数,f该函数后跟参数函数

val g: Int => Int = i => i * 2

val h = f.andThen(g)

h(x)那么是g(f(x))

于 2013-11-29T19:51:42.147 回答