假设我想有条件地构建披萨的配料列表:
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
但是有更好的方法吗?
最佳答案
这是另一种更接近@Antot 的可能方式,但恕我直言,它要简单得多。
您的原始代码中不清楚的是 isVegetarian
和 shouldBeSpicy
的实际来源。这里我假设有一个 PizzaConf
类如下提供这些配置设置
case class PizzaConf(isVegetarian: Boolean, shouldBeSpicy: Boolean)
假设这样,我认为最简单的方法是使用 List[(String, Function1[PizzaConf, Boolean])]
类型的 allIngredients
,即存储配料的类型和检查其相应可用性的功能。假设 buildIngredients
变得微不足道:
val allIngredients: List[(String, Function1[PizzaConf, Boolean])] = List(
("Pepperoni", conf => conf.isVegetarian),
("Jalapeno", conf => conf.shouldBeSpicy)
)
def buildIngredients(pizzaConf: PizzaConf): List[String] = {
allIngredients
.filter(_._2(pizzaConf))
.map(_._1)
}
或者您可以使用 collect
合并 filter
和 map
,如下所示:
def buildIngredients(pizzaConf: PizzaConf): List[String] =
allIngredients.collect({ case (ing, cond) if cond(pizzaConf) => ing })
关于scala - 有条件地构建避免突变的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171101/