2

给定 a List,我想过滤掉任何等于Unit - ()

有没有比通过这段代码更好的过滤方法?

scala> List( () ).filter( x => x != () )
<console>:8: warning: comparing values of types Unit and Unit using `!=' will 
always yield false
                  List( () ).filter( x => x != () )
                                            ^
    res10: List[Unit] = List()
4

3 回答 3

4

我会这样做:

List(1, (), 4, (), 9, (), 16) filter (_ != ())
res0: List[AnyVal] = List(1, 4, 9, 16)
于 2013-10-10T17:06:17.180 回答
3
scala> List(()).filterNot(_.isInstanceOf[Unit])
res0: List[Unit] = List()

scala> List((),1,2).filterNot(_.isInstanceOf[Unit])
res1: List[AnyVal] = List(1, 2)
于 2013-10-10T16:53:35.030 回答
3

您可以使用模式匹配:

list.filter(_ match {
   case x : Unit => false
   case x => true})
于 2013-10-10T16:49:50.650 回答