如何在复制时修改集合中与谓词匹配的元素?

时间:2014-12-29 03:44:31

标签: scala scala-collections

如果符合特定条件,我想复制列表并在复制时修改项目。是否有更好/更快/更惯用的方法来实现这一目标?

class Animal(val t: String, val n : String) {}

val farm =  List[Animal](
  new Animal("pig","squeeky"),
  new Animal("chicken","clucker"),
  new Animal("fox","grr"),
  new Animal("chicken","clucky"),
  new Animal("chicken","cluckster"))

// i want to replace 'fox' with 'deadfox'
val safefarm = farm.map(n => {
  if (n.t == "fox")
    new Animal("deadfox","")
  else n
})

farm.map(_.t)
// res4: List[String] = List(pig, chicken, fox, chicken, chicken)

safefarm.map(_.t)
// res5: List[String] = List(pig, chicken, deadfox, chicken, chicken)

2 个答案:

答案 0 :(得分:5)

通过Animal个案例类并在map中使用模式匹配,您可以更加优雅。

case class Animal(t: String, n : String)

val farm =  List[Animal](
  Animal("pig","squeeky"),
  Animal("chicken","clucker"),
  Animal("fox","grr"),
  Animal("chicken","clucky"),
  Animal("chicken","cluckster")
)

val safefarm = farm map {
  case Animal("fox", _) => Animal("deadfox", "")
  case a => a
}

map只能通过List,因此速度最快。但我认为模式匹配使其更具可读性。

答案 1 :(得分:1)

对于给定case class的更多旁注,copy方法会创建一个新的case class实例,其中所选字段已更改;考虑这个例子:

scala> case class Animal(t: String, n : String)
defined class Animal

scala> val a = Animal("fox","grr")
a: Animal = Animal(fox,grr)

scala> val b = a.copy(t="deadfox")
b: Animal = Animal(deadfox,grr)

此处b: Animala: Animal副本,其中字段t: String已更改。