[英]Implementing hash method in scala classes
I have a base abstract class and several case classes derived from it. 我有一个基础抽象类和从其派生的几个案例类。 I need to have a hash function to identify repeated case objects..Is there any built-in hash method in scala? 我需要一个哈希函数来识别重复的案例对象。.scala中是否有任何内置的哈希方法?
for example, I have a base class 例如,我有一个基类
abstract class CDR_NOR {
val SUBSCRIBER_ID: String
val CHARGING_ID: String
val NODE_ID: String
val START_TIME: String
val hashvalue:Strng
//hashvalue=this.hashCode().toString() doesn't work here
}
and also some derived classes as follow: 还有一些派生类,如下所示:
case class CHG_NOR(Subscriber_ID: String,..., hashvalue:String) extends CDR_NOR
case class NW_NOR(Subscriber_ID: String,...,hashvalue:String) extends CDR_NOR
I need to have a hash function in the base class which make a unique value for each derived class.. 我需要在基类中具有一个哈希函数,该函数为每个派生类赋予唯一的值。
Case classes by default have a hashcode implementation over their constructor parameters. 默认情况下,案例类在其构造函数参数上具有哈希码实现。 You could use that like below and avoid implementing your own hashcode for equality testing. 您可以像下面那样使用它,而避免实现自己的哈希码以进行相等性测试。
abstract class CDR_NOR {
val SUBSCRIBER_ID: String
val CHARGING_ID: String
val NODE_ID: String
val START_TIME: String}
case class CHG_NOR(SUBSCRIBER_ID: String, CHARGING_ID: String, NODE_ID: String, START_TIME: String) extends CDR_NOR
val x = CHG_NOR("001","123","1","12:23AM")
val y = CHG_NOR("001","123","1","12:23AM")
x == y // true
If you want to customize your hashcode implementation, then override hashcode in abstract class like below: 如果要自定义哈希码实现,请在如下的抽象类中覆盖哈希码:
override def hashCode: Int = {// your custom implementation}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.