Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Quantity hashcode method. #307

Merged
merged 2 commits into from
Jun 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion shared/src/main/scala/squants/Quantity.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

package squants

import java.util.Objects

import scala.math.BigDecimal.RoundingMode
import scala.math.BigDecimal.RoundingMode.RoundingMode

Expand Down Expand Up @@ -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)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, the resulting hashCode is not stable across JVM runs because the dimension itself may not have a stable hashCode.

}

/**
* Returns boolean result of approximate equality comparison
Expand Down
16 changes: 16 additions & 0 deletions shared/src/test/scala/squants/QuantitySpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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()

}
}