diff --git a/shared/src/main/scala/squants/Quantity.scala b/shared/src/main/scala/squants/Quantity.scala index 0778bdc2..86439d59 100644 --- a/shared/src/main/scala/squants/Quantity.scala +++ b/shared/src/main/scala/squants/Quantity.scala @@ -8,6 +8,8 @@ package squants +import java.util.Objects + import scala.math.BigDecimal.RoundingMode import scala.math.BigDecimal.RoundingMode.RoundingMode @@ -176,7 +178,9 @@ abstract class Quantity[A <: Quantity[A]] extends Serializable with Ordered[A] { * * @return */ - override def hashCode() = toString.hashCode() + override def hashCode() = { + Objects.hash(dimension, Double.box(to(dimension.primaryUnit))) + } /** * Returns boolean result of approximate equality comparison diff --git a/shared/src/test/scala/squants/QuantitySpec.scala b/shared/src/test/scala/squants/QuantitySpec.scala index 2087af47..8a9738ce 100644 --- a/shared/src/test/scala/squants/QuantitySpec.scala +++ b/shared/src/test/scala/squants/QuantitySpec.scala @@ -686,4 +686,20 @@ class QuantitySpec extends FlatSpec with Matchers with CustomMatchers with TryVa m.failure.exception shouldBe a[QuantityParseException] m.failure.exception should have message("Unable to identify Mass unit m:(100.0,m)") } + + it should "return consistent hashcode" in { + val timeInMinutes = Minutes(1) + + timeInMinutes.hashCode() shouldBe timeInMinutes.hashCode() + } + + it should "return equal hashcode, when objects are equal" in { + + val timeInMinutes = Minutes(1) + val timeInSeconds = Seconds(60) + + timeInMinutes.equals(timeInSeconds) shouldBe true + timeInMinutes.hashCode() shouldBe timeInSeconds.hashCode() + + } }