4
votes

These two records have the same fields with the same values but the order is different:

val person1 = ("age" ->> 34) :: ("name" ->> "Jane") :: HNil
val person2 = ("name" ->> "Jane") :: ("age" ->> 34) :: HNil

These are not considered equal when I use == because the order of the fields is different. They are HLists, so it makes sense to me that the order matters when checking for equality, but I feel like records that are permutations of one another should be equal. I also feel like they should have the same type but they don't because they are HList's.

Is there a way to get equality of values and types for records to act more like what I expect? Also, what are the reasons it is implemented this way? Could HMaps have been used instead?

1

1 Answers

6
votes

You can do something like this using Align.

import shapeless._, syntax.singleton._, record._, ops.hlist._

def permutatedEqual[R1 <: HList, R2 <: HList](
  r1: R1, r2: R2
)(implicit
  align: Align[R1, R2]
): Boolean = align(r1) == r2

Which you can use as :

permutatedEqual(person1, person2) // Boolean = true