Scala: Filtering based on type

前端 未结 5 1179
忘了有多久
忘了有多久 2020-12-24 15:33

I\'m learning Scala as it fits my needs well but I am finding it hard to structure code elegantly. I\'m in a situation where I have a List x and wa

5条回答
  •  执念已碎
    2020-12-24 15:57

    Starting in Scala 2.13, most collections are now provided with a partitionMap method which partitions elements based on a function returning either Right or Left.

    That allows us to pattern match a given type (here Person) that we transform as a Right in order to place it in the right List of the resulting partition tuple. And other types can be transformed as Lefts to be partitioned in the left part:

    // case class Person(name: String)
    // case class Pet(name: String)
    val (pets, persons) =
      List(Person("Walt"), Pet("Donald"), Person("Disney")).partitionMap {
        case person: Person => Right(person)
        case pet: Pet       => Left(pet)
      }
    // persons: List[Person] = List(Person(Walt), Person(Disney))
    // pets: List[Pet] = List(Pet(Donald))
    

提交回复
热议问题