如果State中的所有val都是基本数据类型,那么这很简单。如果我们想在里面复制一个特定的值,它就是
copy(specificValue = newValue)
但是,如果这个特定的值在类内部,该怎么办?这是我试过的,但没有用
copy(specificClass.specificValue = newValue)
我应该在外面创建/复制这个类,然后把它做成下面这样吗?
copy(specificClass = newClass)
如果您有
case class Address(street: String, city: String)
case class User(address: Address, name: String)
val u = User(...)
//to change the city to something else you would do
val another = u.copy(address = u.address.copy(city = "New York")
这很麻烦。我建议使用quicklens
库,它将允许您编写:
import com.softwaremill.quicklens._
val another = u.modify(_.address.city).setTo("New York")
这里有一个名为quicklens 的项目
import com.softwaremill.quicklens._
case class Street(name: String)
case class Address(street: Street)
case class Person(address: Address, age: Int)
val person = Person(Address(Street("1 Functional Rd.")), 35)
val p2 = person.modify(_.address.street.name).using(_.toUpperCase)
val p3 = person.modify(_.address.street.name).setTo("3 OO Ln.")
// or
val p4 = modify(person)(_.address.street.name).using(_.toUpperCase)
val p5 = modify(person)(_.address.street.name).setTo("3 OO Ln.")