diff --git a/kotlin/src/main/java/com/squareup/moshi/kotlin/KotlinJsonAdapter.kt b/kotlin/src/main/java/com/squareup/moshi/kotlin/KotlinJsonAdapter.kt index b50a8c1..048011b 100644 --- a/kotlin/src/main/java/com/squareup/moshi/kotlin/KotlinJsonAdapter.kt +++ b/kotlin/src/main/java/com/squareup/moshi/kotlin/KotlinJsonAdapter.kt @@ -206,6 +206,11 @@ class KotlinJsonAdapterFactory : JsonAdapter.Factory { continue } + if (parameter != null && parameter.type != property.returnType) { + throw IllegalArgumentException("'${property.name}' has a constructor parameter of type " + + "${parameter.type} but a property of type ${property.returnType}.") + } + if (property !is KMutableProperty1 && parameter == null) continue property.isAccessible = true diff --git a/kotlin/src/test/java/com/squareup/moshi/kotlin/KotlinJsonAdapterTest.kt b/kotlin/src/test/java/com/squareup/moshi/kotlin/KotlinJsonAdapterTest.kt index e25f23b..3d896e7 100644 --- a/kotlin/src/test/java/com/squareup/moshi/kotlin/KotlinJsonAdapterTest.kt +++ b/kotlin/src/test/java/com/squareup/moshi/kotlin/KotlinJsonAdapterTest.kt @@ -346,6 +346,21 @@ class KotlinJsonAdapterTest { var b: Int = -1 } + @Test fun constructorParametersAndPropertiesWithSameNamesMustHaveSameTypes() { + val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() + try { + moshi.adapter(ConstructorParameterWithSameNameAsPropertyButDifferentType::class.java) + fail() + } catch (expected: IllegalArgumentException) { + assertThat(expected).hasMessage("'a' has a constructor parameter of type " + + "kotlin.Int but a property of type kotlin.String.") + } + } + + class ConstructorParameterWithSameNameAsPropertyButDifferentType(a: Int) { + var a = "boo" + } + @Test fun supertypeConstructorParameters() { val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() val jsonAdapter = moshi.adapter(SubtypeConstructorParameters::class.java)