我有一个基本抽象类和从中派生的几个案例类。我需要一个哈希函数来识别重复的case对象..在scala中是否有任何内置的哈希方法?
例如,我有一个基类
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
}
以及一些派生类如下:
case class CHG_NOR(Subscriber_ID: String,..., hashvalue:String) extends CDR_NOR
case class NW_NOR(Subscriber_ID: String,...,hashvalue:String) extends CDR_NOR
我需要在基类中有一个哈希函数,它为每个派生类创建一个唯一值。
答案 0 :(得分:0)
默认情况下,Case类在其构造函数参数上具有哈希码实现。您可以像下面那样使用它,并避免实现自己的哈希码进行相等测试。
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
如果要自定义哈希码实现,则覆盖抽象类中的哈希码,如下所示:
override def hashCode: Int = {// your custom implementation}