本文介绍了理解`andThen`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了andThen
,但没有正确理解.
I encountered andThen
, but did not properly understand it.
为了进一步研究,我阅读了 Function1.andThen 文档
To look at it further, I read the Function1.andThen docs
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))
注意 - 来自 DSLs in Action
andThen
强大吗?基于这个例子,它看起来像 mm.andThen
de-sugars to x =>mm.apply(x)
.如果andThen
还有更深的含义,那我还没看懂.
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.
推荐答案
andThen
只是函数组合.给定一个函数 f
andThen
is just function composition. Given a function f
val f: String => Int = s => s.length
andThen
创建一个新函数,它应用 f
后跟参数函数
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)
然后是 g(f(x))
这篇关于理解`andThen`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!