案例类中的var成员会影响案例类的相等性吗? [英] Will the var members in case class affect case class's equality?

查看:73
本文介绍了案例类中的var成员会影响案例类的相等性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中大量使用了case类,对case类的基本相等性定义进行了回复,以使其正常运行。然后,现在我发现我需要在案例类中添加另一个字段成员。

I have made heavy use of case classes in my code, replying on the underlying equality definitions of case class to behave correctly. Then now I found that I need to add another field member to a case class.


  1. 因此,如果我添加 var 案例类中的字段成员,是否会弄乱案例类的相等属性?

  2. 如果1为是,那么如果我只更改一次 var 字段值,此后将不会发生任何重新分配,在case类进入任何集合或进行相等比较之前,这是否还会破坏相等行为?

  1. So if I add a var field member in case class, will it mess up the equality attributes for the case class?
  2. If 1 is yes, then what if I just change the var field value once, after that, no any reassignment will happen, before the case class goes into any collections or do equality comparison, will that still mess up the equality behaviors?


推荐答案

Case类相等性仅基于其主要构造函数属性,无论它们是 var 还是 val (是的,您可以通过给出显式的 var 使其隐含的 val来使它们成为 var case class构造函数args拥有。)在 case class的主体中添加属性 不会影响编译器,生成的 equals(other:Any)方法。

Case class equality is based solely on its primary constructor attributes, whether they're var or val (yes, you can make them var by giving an explicit var to override the implied val that case class constructor args possess.) Adding properties in the body of a case class does not influence the compiler-generated equals(other: Any) method.

见证:

package rrs.scribble

object  CCVarEq
{
  case class CC1(i: Int, j: Float, var k: Double)

  case class CC2(i: Int, j: Float, var k: Double) {
    var l = math.Pi
  }

  def show {
    val cc11 = CC1(1, 2.0f, 3.0)
    val cc12 = CC1(1, 2.0f, 3.0)

    val cc21 = CC2(1, 2.0f, 3.0); cc21.l = math.E
    val cc22 = CC2(1, 2.0f, 3.0)

    printf("cc11 == cc12: %s%n", cc11 == cc12); cc12.k = math.Pi * math.E
    printf("cc11 == cc12: %s%n", cc11 == cc12)

    printf("cc21 == cc22: %s%n", cc21 == cc22)
  }
}

在REPL中:

scala> import rrs.scribble.CCVarEq._
import rrs.scribble.CCVarEq._

scala> show
cc11 == cc12: true
cc11 == cc12: false
cc21 == cc22: true

所有Jamie关于并发的观点也是有效的。

And all jamie's points about concurrency are valid, too.

这篇关于案例类中的var成员会影响案例类的相等性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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