如何在Scala中的对象中复制包装在选项内的对象

时间:2019-02-08 15:06:17

标签: scala

我在Scala中具有以下结构-

case class SomeObject (name: String, anotherObject: Option[AnotherObject])
case class AnotherObject (value1: Array[String], value2: String, value3: String)

现在,我想复制已实例化的SomeObject,如下所示。

SomeObject.copy(anotherObject = SomeObject.anotherObject.copy
                                (value3 = <SomeAnotherValue>))

这不起作用,请提出可能的解决方案。

2 个答案:

答案 0 :(得分:2)

我相信,问题在于 Option 没有copy方法,而您想调用 AnotherObject copy方法

假设您只想更改内部值,如果变量存在(表示它是 Some ,那么您可以map < strong>选项以获取 AnotherObject 实例。
为了简化多次调用,我在您的 SomeObject 类中创建了一个aux方法,以封装逻辑。

final case class AnotherObject(value1: Array[String], value2: String, value3: String)
final case class SomeObject(name: String, anotherObject: Option[AnotherObject]) {
  def changeInnerValue3(newValue: String): SomeObject =
    this.copy(
      anotherObject = this.anotherObject.map(ao => ao.copy(value3 = newValue))
    )
}

SomeObject(name = "so", anotherObject = Some(AnotherObject(value1 = Array.empty, value2 = "Hello", value3 = "World!")))
// res1: SomeObject = SomeObject(so,Some(AnotherObject([Ljava.lang.String;@52bba91a,Hello,World!)))

res1.changeInnerValue3(newValue = "You")
// res2: SomeObject = SomeObject(so,Some(AnotherObject([Ljava.lang.String;@52bba91a,Hello,You)))

答案 1 :(得分:0)

您只需要使用copy,在Option内的对象上调用Option,而不是map本身:

SomeObject.copy(anotherObject = SomeObject.anotherObject.map(_.copy
                            (value3 = <SomeAnotherValue>)))