我目前正在映射一個集合進行驗證,我需要回傳一個或多個驗證錯誤:
val errors: Seq[Option[ProductErrors]] = products.map {
if(....) Some(ProductError(...))
else if(...) Some(ProductError(..))
else None
}
errors.flatten
所以目前我在每次地圖迭代時回傳一個 Option[ProductError],但在某些情況下我需要回傳多個 ProductError,我該如何實作呢?例如
if(...) {
val p1 = Some(ProductError(...))
val p2 = Some(ProductError(....))
}
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/415351.html
標籤:
