diff --git a/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/AdapterGenerator.kt b/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/AdapterGenerator.kt index 3c4f7a2..ce6cfed 100644 --- a/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/AdapterGenerator.kt +++ b/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/AdapterGenerator.kt @@ -160,7 +160,15 @@ internal class AdapterGenerator( .build() fun prepare(typeHook: (TypeSpec) -> TypeSpec = { it }): PreparedAdapter { + val reservedSimpleNames = mutableSetOf() for (property in nonTransientProperties) { + // Allocate names for simple property types first to avoid collisions + // See https://github.com/square/moshi/issues/1277 + property.target.type.findRawType()?.simpleName?.let { simpleNameToReserve -> + if (reservedSimpleNames.add(simpleNameToReserve)) { + nameAllocator.newName(simpleNameToReserve) + } + } property.allocateNames(nameAllocator) } diff --git a/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/kotlintypes.kt b/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/kotlintypes.kt index 9f1a776..5dcbb91 100644 --- a/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/kotlintypes.kt +++ b/kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/kotlintypes.kt @@ -39,10 +39,14 @@ import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asTypeName internal fun TypeName.rawType(): ClassName { + return findRawType() ?: throw IllegalArgumentException("Cannot get raw type from $this") +} + +internal fun TypeName.findRawType(): ClassName? { return when (this) { is ClassName -> this is ParameterizedTypeName -> rawType - else -> throw IllegalArgumentException("Cannot get raw type from $this") + else -> null } } diff --git a/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/codegen/GeneratedAdaptersTest.kt b/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/codegen/GeneratedAdaptersTest.kt index 27286e8..410cda5 100644 --- a/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/codegen/GeneratedAdaptersTest.kt +++ b/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/codegen/GeneratedAdaptersTest.kt @@ -1363,6 +1363,16 @@ class GeneratedAdaptersTest { data class MultipleGenerics(val prop: String) } +// Regression test for https://github.com/square/moshi/issues/1277 +// Compile-only test +@JsonClass(generateAdapter = true) +data class OtherTestModel(val TestModel: TestModel? = null) +@JsonClass(generateAdapter = true) +data class TestModel( + val someVariable: Int, + val anotherVariable: String +) + // Regression test for https://github.com/square/moshi/issues/1022 // Compile-only test @JsonClass(generateAdapter = true)