Skip to content

Commit

Permalink
Fix Quantity hashcode method. (typelevel#307)
Browse files Browse the repository at this point in the history
* Fix Quantity hashcode method. Previous version was broken equals/hashcode conduct.

* Add hashcode method tests.
  • Loading branch information
Passarinho4 authored and derekmorr committed Jun 4, 2018
1 parent e50bc75 commit ed961e4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
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)))
}

/**
* 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()

}
}

0 comments on commit ed961e4

Please sign in to comment.