映射可能 return 多个值或单个值的集合

Mapping over a collection that might return multiple values or a single value

我目前正在映射一个集合以进行验证,我需要return返回一个或多个验证错误:

val errors: Seq[Option[ProductErrors]] = products.map {
   if(....) Some(ProductError(...))
   else if(...) Some(ProductError(..))
   else None

}
errors.flatten

所以目前我在每个地图迭代中 return 设置一个选项 [ProductError],但在某些情况下我需要 return 多个 ProductError,我该如何实现? 例如

   if(...) {
     val p1 = Some(ProductError(...))
     val p2 = Some(ProductError(....))
   }
case class ProductErrors(msg: String = "anything")

val products = (1 to 10).toList

def convert(p: Int): Seq[ProductErrors] = {
  if (p < 5) Seq(ProductErrors("less than 5"))
  else if (p < 8 && p % 2 == 1) Seq(ProductErrors("element is odd"), ProductErrors("less than 8"))
  else Seq()
}

val errors = products.map(convert)


// errors.flatten.size
// val res8: Int = 8

// you can just use flatMap here

products.flatMap(convert).size // 8