Scala对象克隆(复制),无需重新评估值

psi*_*yev 4 clone scala copy

我有一个大对象:

case class BigObject(val str: String, val number: Int) {
val someVal = ...
val someVal2 = ...
    }
Run Code Online (Sandbox Code Playgroud)

我想复制这个对象而不重新评估值.可能吗?现在我正在使用这种方法:

val newBigObject = oldBigObject.copy(str = newStr)
Run Code Online (Sandbox Code Playgroud)

正如我从日志/调试器中看到的那样,"someVal"和"someVal2"被重新评估.有可能避免它吗?由于我的BigObject非常庞大,价值重估需要一些时间,但性能对我来说非常重要.

谢谢你的回答!

Mar*_*ila 7

这是一种方式:

使someValsomeVal2这也传递给构造领域,拉出初始化逻辑在同伴对象的字段.

在你的情况下:

class BigObject private(val str: String,
                        val number: Int,
                        val someVal: SomeType,
                        val someVal2: SomeType) {

   def copy(newStr: String = str, newNumber: Int = number) = {
     new BigObject(newStr, newNumber, someVal, someVal2)
   }
}

object BigObject {

  def apply(str: String, number: Int): BigObject = {
    val someVal = initialize() //your initialization logic here
    val someVal2 = initialize2()
    new BigObject(str, number, someVal, someVal2)
  }

}
Run Code Online (Sandbox Code Playgroud)

现在,您无需重新评估内部字段即可进行复制:

val bigObj = BigObject("hello", 42)
val anotherBigObj = bigObj.copy(newStr = "anotherStr")
Run Code Online (Sandbox Code Playgroud)

或者,如果您不喜欢伴侣对象,则可以创建两个构造函数.主要的一个包括所有字段(也是不可见的字段)并且是私有的.公众将只有两个可见参数:

class BigObject private(val str: String,
                        val number: Int,
                        val someVal: Any,
                        val someVal2: Any) {

  def this(str: String, number: Int) = this(str, number, initializeVal, initializeVal2)

  def copy(newStr: String = str, newNumber: Int = number) = {
    new BigObject(newStr, newNumber, someVal, someVal2)
  }

}
Run Code Online (Sandbox Code Playgroud)

用法:

val bigObj = new BigObject("hello", 42)
val anotherBigObj = bigObj.copy(newStr = "anotherStr")
Run Code Online (Sandbox Code Playgroud)