List filter

Given a List , I would like to filter out any elements that are equal to Unit - () .

Is there a better filtering method than through this code?

 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() 
+2
source share
3 answers

I would go with this:

 List(1, (), 4, (), 9, (), 16) filter (_ != ()) res0: List[AnyVal] = List(1, 4, 9, 16) 
+3
source

You can use pattern matching:

 list.filter(_ match { case x : Unit => false case x => true}) 
+3
source
 scala> List(()).filterNot(_.isInstanceOf[Unit]) res0: List[Unit] = List() scala> List((),1,2).filterNot(_.isInstanceOf[Unit]) res1: List[AnyVal] = List(1, 2) 
+3
source

Source: https://habr.com/ru/post/955703/


All Articles