From 834a4011226ec0ed6d6186831ad8351051e1fb09 Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Sat, 17 Feb 2018 19:51:02 -0800 Subject: [PATCH] Crash earlier for property type conflicts. (#377) --- .../squareup/moshi/kotlin/KotlinJsonAdapter.kt | 5 +++++ .../moshi/kotlin/KotlinJsonAdapterTest.kt | 15 +++++++++++++++ 2 files changed, 20 insertions(+) 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)