scala - 有条件地构建避免突变的列表

标签 scala collections

假设我想有条件地构建披萨的配料列表:

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 的可能方式,但恕我直言,它要简单得多。

您的原始代码中不清楚的是 isVegetarianshouldBeSpicy 的实际来源。这里我假设有一个 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 合并 filtermap,如下所示:

def buildIngredients(pizzaConf: PizzaConf): List[String] = 
  allIngredients.collect({ case (ing, cond) if cond(pizzaConf) => ing })

关于scala - 有条件地构建避免突变的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171101/

相关文章:

scala - 为什么 akka-http Unmarshaler 返回 Future[T] 而不是 T?

json - 使用 Argonaut 或 Circe 从不完整的 JSON 更新案例类

web-services - Web 服务调用上的 Scala Play2 错误

scala - 使用 MRUnit 1.1.0 测试多个输出

c# - .net FIFO "Queue"结合最后一个已知主题

c# - 从自定义集合中检索项目

Magento 集合表达式

scala - 使用spark scala远程连接hbase

java - 随机排列数组列表,不重复

java - 查找集合中的最后一个引用