Scala filter on two conditions

前端 未结 3 1823
自闭症患者
自闭症患者 2021-02-02 05:47

I would like to filter my data set on two conditions at once.

Is it possible?

I want something like this:

mystuff = mystuff.filter(_.isX &         


        
3条回答
  •  渐次进展
    2021-02-02 06:44

    If you need to frequently filter with several predicate, you could define a way of combining them:

    case class And[A]( p1: A=>Boolean, p2: A=>Boolean ) extends (A=>Boolean) {
      def apply( a: A ) = p1(a) && p2(a)
    }
    

    Here is how to use it to keep only the odd numbers bigger than 10:

    scala> (0 until 20) filter And( _ > 10, _ % 2 == 1 )
    res3: scala.collection.immutable.IndexedSeq[Int] = Vector(11, 13, 15, 17, 19)
    

    It easy to write Or and Not combinators in the same fashion.

提交回复
热议问题