【发布时间】:2018-05-04 09:00:00
【问题描述】:
假设我想有条件地构建 Pizza 的成分列表:
val ingredients = scala.collection.mutable.ArrayBuffer("tomatoes", "cheese")
if (!isVegetarian()) {
ingredients += "Pepperoni"
}
if (shouldBeSpicy()) {
ingredients += "Jalapeno"
}
//etc
有没有使用不可变集合构建这个数组的功能性方法?
我想过:
val ingredients = List("tomatoes", "cheese") ++ List(
if (!isVegetarian()) Some("Pepperoni") else None,
if (shouldBeSpicy()) Some("Jalapeno") else None
).flatten
但是有更好的方法吗?
【问题讨论】:
标签: scala collections