This gist contains a Scala 3 macro that compares two entities field by field, automatically skipping any fields where exactly one of the values is null
. The comparison logic is generated at compile time using Scala's quoted API, which ensures no runtime reflection overhead.
- Compare two entities of any type.
- Skip fields with
null
values based on predefined business rules. - Avoid runtime reflection by generating code at compile time.
The example compares two Address
objects:
@main def main(): Unit = {
val testCases = List(
(("USA", null, "New York"), ("USA", "NY", null)), // true
((null, null, null), (null, null, null)), // true
(("USA", null, null), ("USA", null, null)), // true
(("Germany", "Berlin", "Berlin"), ("Germany", "Berlin", null)), // true
(("France", "Paris", "Lyon"), ("France", "Paris", "Lyon")), // true
(("Canada", null, "Toronto"), ("Canada", "Ontario", "Toronto")), // true
((null, "California", null), (null, "California", "Los Angeles")), // true
(("Italy", "Rome", null), ("Italy", null, "Rome")), // true
(("Japan", "Tokyo", "Shibuya"), ("Japan", "Kyoto", "Osaka")), // false
(("Poland", null, "New York"), ("USA", "NY", null)), // false
)
testCases.foreach { case (a, b) =>
val addrA = Address(a._1, a._2, a._3)
val addrB = Address(b._1, b._2, b._3)
println(compareEntity(addrA, addrB))
}
}
case class Address(country: String, state: String, city: String)