Scala:忽略equals / hascode的案例类字段? [英] Scala: Ignore case class field for equals/hascode?

查看:119
本文介绍了Scala:忽略equals / hascode的案例类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以忽略案例类的equals / haschode方法中的案例类的字段吗?



我的使用案例是,我有一个字段,基本上是类中其余数据的元数据。

 解决方案

只有第一个参数部分中的参数被考虑用于平等和散列。 scala> case类Foo(a:Int)(b:Int)
定义类Foo

scala> Foo(0)(0)== Foo(0)(1)
res0:Boolean = true

scala> Seq(0,1).map(Foo(0)(_)。hashCode)
res1:Seq [Int] = List(-1669410282,-1669410282)
/ pre>

UPDATE



显示 / code>作为字段:

  scala> case类Foo(a:Int)(val b:Int)
定义类Foo

scala> Foo(0)(1).b
res3:Int = 1


Is it possible to ignore a field of a case class in the equals/haschode method of the case class?

My use case is that I have a field that is essentially metadata for rest of the data in the class.

解决方案

Only parameters in the first parameter section are considered for equality and hashing.

scala> case class Foo(a: Int)(b: Int)
defined class Foo

scala> Foo(0)(0) == Foo(0)(1)
res0: Boolean = true

scala> Seq(0, 1).map(Foo(0)(_).hashCode)
res1: Seq[Int] = List(-1669410282, -1669410282)

UPDATE

To expose b as a field:

scala> case class Foo(a: Int)(val b: Int)
defined class Foo

scala> Foo(0)(1).b
res3: Int = 1

这篇关于Scala:忽略equals / hascode的案例类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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