Skip to content

Commit

Permalink
Don't add canEqual and equals if users already defined them
Browse files Browse the repository at this point in the history
  • Loading branch information
alexarchambault committed Jan 16, 2025
1 parent 8bdb2bb commit d5c4241
Showing 1 changed file with 30 additions and 26 deletions.
56 changes: 30 additions & 26 deletions src/main/scala/dataclass/Macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -124,33 +124,37 @@ private[dataclass] class Macros(val c: Context) extends ImplTransformers {
tq"({type L[..$tparams0]=$WildcardType})#L"
}

val canEqualMethod = {
val hashCheck =
if (cachedHashCode) q"obj.hashCode == hashCode" else q"true"
Seq(
q"""
override def canEqual(obj: Any): _root_.scala.Boolean =
obj != null && obj.isInstanceOf[$tpname[..$wildcardedTparams]] && $hashCheck
"""
)
}
val canEqualMethod =
if (hasCanEqual) Nil
else {
val hashCheck =
if (cachedHashCode) q"obj.hashCode == hashCode" else q"true"
Seq(
q"""
override def canEqual(obj: Any): _root_.scala.Boolean =
obj != null && obj.isInstanceOf[$tpname[..$wildcardedTparams]] && $hashCheck
"""
)
}

val equalsMethod = {
val fldChecks = paramss.flatten
.map { param =>
q"this.${param.name} == other.${param.name}"
}
.foldLeft[Tree](q"true")((a, b) => q"$a && $b")
Seq(
q"""
override def equals(obj: Any): _root_.scala.Boolean =
this.eq(obj.asInstanceOf[AnyRef]) || canEqual(obj) && {
val other = obj.asInstanceOf[$tpname[..$wildcardedTparams]]
$fldChecks
}
"""
)
}
val equalsMethod =
if (hasEquals) Nil
else {
val fldChecks = paramss.flatten
.map { param =>
q"this.${param.name} == other.${param.name}"
}
.foldLeft[Tree](q"true")((a, b) => q"$a && $b")
Seq(
q"""
override def equals(obj: Any): _root_.scala.Boolean =
this.eq(obj.asInstanceOf[AnyRef]) || canEqual(obj) && {
val other = obj.asInstanceOf[$tpname[..$wildcardedTparams]]
$fldChecks
}
"""
)
}

val hashCodeMethod =
if (hasHashCode) Nil
Expand Down

0 comments on commit d5c4241

Please sign in to comment.