Skip to content

Commit 1574cec

Browse files
authored
refactor: generate KMP versions of equals and hashCode (#545)
1 parent db1d165 commit 1574cec

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/rendering/StructureGenerator.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,17 +118,17 @@ class StructureGenerator(
118118
writer.write("")
119119
writer.withBlock("override fun hashCode(): #Q {", "}", KotlinTypes.Int) {
120120
when {
121-
sortedMembers.isEmpty() -> write("var result = javaClass.hashCode()")
121+
sortedMembers.isEmpty() -> write("return this::class.hashCode()")
122122
else -> {
123123
write("var result = #1L#2L", memberNameSymbolIndex[sortedMembers[0]]!!.first, selectHashFunctionForShape(sortedMembers[0]))
124124
if (sortedMembers.size > 1) {
125125
sortedMembers.drop(1).forEach { memberShape ->
126126
write("result = 31 * result + (#1L#2L)", memberNameSymbolIndex[memberShape]!!.first, selectHashFunctionForShape(memberShape))
127127
}
128128
}
129+
write("return result")
129130
}
130131
}
131-
write("return result")
132132
}
133133
}
134134

@@ -170,7 +170,7 @@ class StructureGenerator(
170170
writer.write("")
171171
writer.withBlock("override fun equals(other: #Q?): #Q {", "}", KotlinTypes.Any, KotlinTypes.Boolean) {
172172
write("if (this === other) return true")
173-
write("if (javaClass != other?.javaClass) return false")
173+
write("if (other == null || this::class != other::class) return false")
174174
write("")
175175
write("other as #T", symbol)
176176
write("")

smithy-kotlin-codegen/src/test/kotlin/software/amazon/smithy/kotlin/codegen/rendering/StructureGeneratorTest.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ class StructureGeneratorTest {
134134
val expected = """
135135
override fun equals(other: kotlin.Any?): kotlin.Boolean {
136136
if (this === other) return true
137-
if (javaClass != other?.javaClass) return false
137+
if (other == null || this::class != other::class) return false
138138
139139
other as MyStruct
140140
@@ -303,7 +303,7 @@ class StructureGeneratorTest {
303303
val expectedEqualsContent = """
304304
override fun equals(other: kotlin.Any?): kotlin.Boolean {
305305
if (this === other) return true
306-
if (javaClass != other?.javaClass) return false
306+
if (other == null || this::class != other::class) return false
307307
308308
other as MyStruct
309309

0 commit comments

Comments
 (0)