diff --git a/core/shared/src/main/scala/tech/ant8e/uuid4cats/TypeID.scala b/core/shared/src/main/scala/tech/ant8e/uuid4cats/TypeID.scala index acf2ac9..1321f1c 100644 --- a/core/shared/src/main/scala/tech/ant8e/uuid4cats/TypeID.scala +++ b/core/shared/src/main/scala/tech/ant8e/uuid4cats/TypeID.scala @@ -202,6 +202,13 @@ object TypeID { case _ => false } + private lazy val hashCodeComputation: Int = { + val prime = 31 + prime * (prime + prefix_.hashCode) + uuid_.hashCode + } + + override def hashCode(): Int = hashCodeComputation + } private[uuid4cats] def validatePrefix( diff --git a/core/shared/src/test/scala/tech/ant8e/uuid4cats/TypeIDSuite.scala b/core/shared/src/test/scala/tech/ant8e/uuid4cats/TypeIDSuite.scala index 2b750d4..fef743b 100644 --- a/core/shared/src/test/scala/tech/ant8e/uuid4cats/TypeIDSuite.scala +++ b/core/shared/src/test/scala/tech/ant8e/uuid4cats/TypeIDSuite.scala @@ -259,6 +259,23 @@ class TypeIDSuite extends FunSuite { ) } + test("TypeID should have a hashCode") { + val idString = "prefix_01h455vb4pex5vsknk084sn02q" + val id1_1 = TypeID.decode(idString).toOption.get + val id1_2 = TypeID.decode(idString).toOption.get + val id2 = TypeID.decode("prefix_01h455vb4pex5vsknk084sn02r").toOption.get + assertEquals( + id1_1.hashCode, + id1_2.hashCode, + "hashCode should be consistent for same data in different instances" + ) + assertNotEquals( + id1_1.hashCode, + id2.hashCode, + "hashCode should be different for different data" + ) + } + private def assertValidEncoding( typeID: String, prefix: String,