如果符合特定条件,我想复制列表并在复制时修改项目。是否有更好/更快/更惯用的方法来实现这一目标?
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)
答案 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: Animal
是a: Animal
的副本,其中字段t: String
已更改。