Scala案例类使用浅拷贝还是深拷贝? [英] Scala case class uses shallow copy or deep copy?

查看:917
本文介绍了Scala案例类使用浅拷贝还是深拷贝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

case class Person(var firstname: String, lastname: String)

val p1 = Person("amit", "shah")
val p2 = p1.copy()
p1.firstname = "raghu"
p1
p2

p1 == p2

当我浏览一些文档时,它说明了scala复制方法 案例类使用浅表复制

As i went through some documentation which says scala copy method of case class uses shallow copy

但此示例的输出我无法破解

but output of this example i am not able to crack

我已经从p1创建为个人p2的副本,然后我进行了更改 p1.firstname为"raghu"

i have created copy as person p2 from p1 and then i have changed p1.firstname to "raghu"

因此,在浅拷贝的情况下,应更改p2.firstname的值 但这不是在这里发生

so, in case of shallow copy it should change value of p2.firstname but this is not happening here

参考: https://docs.scala-lang.org/tour/case-classes.html

推荐答案

您的困惑是关于variablesvalues之间的区别.

Your confusion is about the difference between variables and values.

所以,当您执行类似操作时,

So, when you do something like,

val p1 = Person("amit", "shah")
val p2 = p1.copy()

然后p2p1的浅表副本,因此variables p1.firstnamep2.firstname指向与String类型相同的value,即"amit".

Then p2 is a shallow copy of p1, so the variables p1.firstname and p2.firstname point to the same value of String type which is "amit".

在执行p1.firstname = "raghu"时,实际上是在告诉变量p1.firstname指向String类型的另一个value,即"raghu".在这里,您不是在更改值本身,而是在variable.

When you are doing p1.firstname = "raghu", you are actually telling variable p1.firstname to point to a different value of String type which is "raghu". Here you are not changing the value itself but the variable.

如果要更改为value本身,则p1p2都将反映该更改.不幸的是,String值在Scala中是不可变的,因此您不能修改String值.

If you were to change to value itself, then both p1 and p2 will reflect the change. Unfortunately, String values are immutable in Scala, so you can not modify a String value.

让我通过使用诸如ArrayBuffer之类的可修改内容向您展示.

Let me show you by using something modifiable like a ArrayBuffer.

scala> import scala.collection.mutable.ArrayBuffer
// import scala.collection.mutable.ArrayBuffer

scala> case class A(s: String, l: ArrayBuffer[Int])
// defined class A

scala> val a1 = A("well", ArrayBuffer(1, 2, 3, 4))
// a1: A = A(well,ArrayBuffer(1, 2, 3, 4))

scala> val a2 = a1.copy()
// a2: A = A(well,ArrayBuffer(1, 2, 3, 4))

// Lets modify the `value` pointed by `a1.l` by removing the element at index 1
scala> a1.l.remove(1)
// res0: Int = 2

// You will see the impact in both a1 and a2.

scala> a1
// res1: A = A(well,ArrayBuffer(1, 3, 4))

scala> a2
//res2: A = A(well,ArrayBuffer(1, 3, 4))

这篇关于Scala案例类使用浅拷贝还是深拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆