Equality of formless expandable records depends on field order

These two entries 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

They 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 order matters when checking equality, but I feel that the entries, which are permutations of each other, should be equal. I also feel that they must be of the same type, but they are not because they are HList.

Is there a way to get equality of values ​​and types for the entries to be more like what I expect? In addition, what are the reasons for its implementation in this way? Can it be HMapused?

+4
source share
1 answer

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

What you can use as:

permutatedEqual(person1, person2) // Boolean = true
+6
source

Source: https://habr.com/ru/post/1609210/


All Articles