如何在状态中复制 class?
how to copy a class inside of a state?
如果State中所有的val都是基本数据类型就很简单了。如果我们想在其中复制一个特定的值,它只是
copy(specificValue = newValue)
但是如果这个特定值在 class 内怎么办?这是我试过但无济于事
copy(specificClass.specificValue = newValue)
我应该 create/copy 这个 class 在外面,然后像下面这样吗?
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.")
如果State中所有的val都是基本数据类型就很简单了。如果我们想在其中复制一个特定的值,它只是
copy(specificValue = newValue)
但是如果这个特定值在 class 内怎么办?这是我试过但无济于事
copy(specificClass.specificValue = newValue)
我应该 create/copy 这个 class 在外面,然后像下面这样吗?
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.")