How to combine filter and map in Scala?

后端 未结 6 612
不知归路
不知归路 2020-12-28 13:10

I have List[Int] in Scala. The List is List(1,2,3,4,5,6,7,8,9,10). I want to filter the list so that it only has even numbers. And I w

6条回答
  •  长情又很酷
    2020-12-28 13:41

    As @cmbaxter said, collect suits your need perfectly. The other nice thing about collect is that it figures out resulting type in case you're filtering by class:

    scala> trait X
    // defined trait X
    
    scala> class Foo extends X
    // defined class Foo
    
    scala> class Bar extends X
    // defined class Bar
    
    scala> val xs = List(new Foo, new Bar, new Foo, new Bar)
    // xs: List[X] = List(Foo@4cfa8227, Bar@78226c36, Foo@3f685162, Bar@11f406f8)
    
    scala> xs.collect { case x: Foo => x }
    // res1: List[Foo] = List(Foo@4cfa8227, Foo@3f685162)
    

    On par, filter can't be that smart (see List[Foo] vs List[X]):

    scala> xs.filter { case x: Foo => true; case _ => false }
    // res3: List[X] = List(Foo@4cfa8227, Foo@3f685162)
    

提交回复
热议问题