在scala中,case类是不可变的。
制作带有多个选项的案例类的修改副本的最佳方法是什么?
例如:
case class Person(name:String, age:Int, something:Option[String])
val maybeName = Some("alice")
val maybeAge = Some(20)
val maybeSomething = Some("hi")
var myNewCaseClass = myCaseClass.???
答案 0 :(得分:3)
这可能就是您想要做的:
val myNewCaseClass: Option[Person] = for {
name <- maybeName
age <- maybeAge
} yield Person(name, age, maybeSomething)
答案 1 :(得分:2)
一种尴尬的方法是对myCaseClass
上的每个属性使用原始值的getOrElse。
如果选择case类的val,则可以使用.orElse(感谢Thilo)
val myNewCaseClass = myCaseClass.copy(
name = maybeName.getOrElse(myCaseClass.name),
age = maybeAge.getOrElse(myCaseClass.age),
something = maybeSomething.orElse(myCaseClass.something)
)
答案 2 :(得分:1)
我看不到任何好的方法来做...
val v1 = maybeAge.map(age => myCaseClass.copy(age = age)).getOrElse(myCaseClass)
val v2 = maybeName.map(name => v1.copy(name = name).getOrElse(v1)
val v3 = maybeSomething.map(something => v2.copy(something = something)).getOrElse(v2)