简体   繁体   中英

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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM