鉴于这两个功能:
scala> def maybe(x: Int): Boolean = x % 2 == 0
maybe: (x: Int)Boolean
scala> def good(x: Int): Boolean = x == 10
good: (x: Int)Boolean
我可以同时应用good
和maybe
个功能吗?
scala> List(10) filter good filter maybe
res104: List[Int] = List(10)
scala> List(10) filter (good && maybe)
<console>:17: error: missing arguments for method good;
follow this method with `_' if you want to treat it as a partially applied function
List(10) filter (good && maybe)
^
答案 0 :(得分:4)
您可以在匿名函数中评估它们:
List(10) filter { x => good(x) && maybe(x) }
你不能真正使用andThen
因为组合就像传递属性。
[(A => Boolean) && (A => Boolean)] != [(A => B) => C]
// ^ What you want ^ Composition
答案 1 :(得分:3)
scala> def maybe(x: Int): Boolean = x % 2 == 0
maybe: (x: Int)Boolean
scala> def good(x: Int): Boolean = x % 3 == 0
good: (x: Int)Boolean
scala> (1 to 20) filter { i => List(good _, maybe _).forall(_(i)) }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(6, 12, 18)