richs
richs

Reputation: 4769

separate scala list based on matching pattern

i have a list of the following scala trait. How can i separate the list into two, one containing only ValidatedSbcCommand objects and other only containing FailedValidationSbcCommand objects?

sealed trait SbcCommandorOrValidationError 
case class ValidatedSbcCommand(sbcCommand: SbcCommand) extends SbcC  ommandorOrValidationError
case class FailedValidationSbcCommand(sbcCommandError: SbcCommandError) extends SbcCommandorOr

Upvotes: 0

Views: 97

Answers (4)

Valy Dia
Valy Dia

Reputation: 2851

From Scala 2.13, you can use of partitionMap, which does exactly what you want, keeping the subtype info:

 list partitionMap {
    case v: ValidatedSbcCommand => Left(v)
    case f: FailedValidationSbcCommand => Right(f)
 }

Upvotes: 0

Vidya
Vidya

Reputation: 30310

I prefer using partition with pattern matching. Given list is of type List[SbcCommandorOrValidationError] and contains only ValidatedSbcCommands and FailedValidationSbcCommands, you can do this:

val (validatedCommands, failedCommands) = list.partition {
  case command: ValidatedSbcCommand => true
  case _ => false
}

This will return a tuple of type (List[SbcCommandorOrValidationError], List[SbcCommandorOrValidationError]) where the first list is all the ValidatedSbcCommands and the second is all the FailedValidationSbcCommands.

If you need to access the specific subclass later on, don't cast. Use pattern matching as above:

validatedCommands.map { 
  case c: ValidatedSbcCommand => functionTakingValidatedSbcCommandsOnly(c) 
}

Upvotes: 1

Shawn Xiong
Shawn Xiong

Reputation: 480

 val result = originalList.foldRight(Tuple2(List[ValidatedSbcCommand](), List[FailedValidationSbcCommand]())){ (start, rest) =>
        start match {
          case a:ValidatedSbcCommand => (a::rest._1, rest._2)
          case b:FailedValidationSbcCommand => (rest._1, b::rest._2)
          case _ => rest
        }
    }

Then result._1 will give you a list of ValidatedSbcCommand, and result._2 will give you a list of FailedValidationSbcCommand.

Upvotes: 1

puhlen
puhlen

Reputation: 8529

Use the partition method on list. It takes a predicate and produces a (List, List) The first list is for the true case the second is for false.

Upvotes: 1

Related Questions