codegen-java/kotlin: Fix generation of hashCode methods (#802)

codegen-java:
- use `pattern.pattern()` instead of `pattern` in hashCode method
  (consistent with equals method)

codegen-kotlin:
- use `regex.pattern` instead of `regex` in hashCode method
  (consistent with equals method)
- if a data class has a Regex property, generate not only
  an equals method but also a hashCode method
This commit is contained in:
translatenix
2024-11-13 15:42:45 -08:00
committed by GitHub
parent b8d90eddec
commit df38011c9e
5 changed files with 39 additions and 16 deletions

View File

@@ -221,6 +221,9 @@ class JavaCodeGenerator(
val properties = renameIfReservedWord(pClass.properties).filterValues { !it.isHidden }
val allProperties = superProperties + properties
fun PClass.Property.isRegex(): Boolean =
(this.type as? PType.Class)?.pClass?.info == PClassInfo.Regex
fun addCtorParameter(
builder: MethodSpec.Builder,
propJavaName: String,
@@ -283,9 +286,7 @@ class JavaCodeGenerator(
.addStatement("\$T other = (\$T) obj", javaPoetClassName, javaPoetClassName)
for ((propertyName, property) in allProperties) {
val accessor =
if ((property.type as? PType.Class)?.pClass?.info == PClassInfo.Regex) "\$N.pattern()"
else "\$N"
val accessor = if (property.isRegex()) "\$N.pattern()" else "\$N"
builder.addStatement(
"if (!\$T.equals(this.$accessor, other.$accessor)) return false",
Objects::class.java,
@@ -306,9 +307,10 @@ class JavaCodeGenerator(
.returns(Int::class.java)
.addStatement("int result = 1")
for (propertyName in allProperties.keys) {
for ((propertyName, property) in allProperties) {
val accessor = if (property.isRegex()) "this.\$N.pattern()" else "this.\$N"
builder.addStatement(
"result = 31 * result + \$T.hashCode(this.\$N)",
"result = 31 * result + \$T.hashCode($accessor)",
Objects::class.java,
propertyName
)

View File

@@ -306,7 +306,7 @@ public final class Mod {
result = 31 * result + Objects.hashCode(this.container);
result = 31 * result + Objects.hashCode(this.container2);
result = 31 * result + Objects.hashCode(this.other);
result = 31 * result + Objects.hashCode(this.regex);
result = 31 * result + Objects.hashCode(this.regex.pattern());
result = 31 * result + Objects.hashCode(this.any);
result = 31 * result + Objects.hashCode(this.nonNull);
result = 31 * result + Objects.hashCode(this._enum);