From 54aca07ca16360047e527a2dcea67ac35a074177 Mon Sep 17 00:00:00 2001 From: Zac Sweers Date: Fri, 4 May 2018 12:11:41 -0700 Subject: [PATCH] Fix nullable properties of TypeVariable types We were forgetting to apply the property's nullability to the resolved type. Fixes #521 --- .../src/main/java/com/squareup/moshi/DelegateKey.kt | 2 +- .../src/main/java/com/squareup/moshi/metadata.kt | 1 + .../kotlin/com/squareup/moshi/GeneratedAdaptersTest.kt | 9 ++++++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/DelegateKey.kt b/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/DelegateKey.kt index c39e3c1..40e22b9 100644 --- a/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/DelegateKey.kt +++ b/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/DelegateKey.kt @@ -33,7 +33,7 @@ internal data class DelegateKey( private val type: TypeName, private val jsonQualifiers: Set ) { - val nullable get() = type.nullable || type is TypeVariableName + val nullable get() = type.nullable /** Returns an adapter to use when encoding and decoding this property. */ fun generateProperty( diff --git a/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/metadata.kt b/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/metadata.kt index 03c2b1e..1109cfb 100644 --- a/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/metadata.kt +++ b/kotlin-codegen/compiler/src/main/java/com/squareup/moshi/metadata.kt @@ -80,6 +80,7 @@ internal fun Type.asTypeName( val realType = when { hasTypeParameter() -> return getTypeParameter(typeParameter) .asTypeName(nameResolver, getTypeParameter, resolveAliases) + .let { if (nullable) it.asNullable() else it } hasTypeParameterName() -> typeParameterName hasAbbreviatedType() && !resolveAliases -> abbreviatedType.typeAliasName else -> className diff --git a/kotlin-codegen/integration-test/src/test/kotlin/com/squareup/moshi/GeneratedAdaptersTest.kt b/kotlin-codegen/integration-test/src/test/kotlin/com/squareup/moshi/GeneratedAdaptersTest.kt index 60bc77c..44060d3 100644 --- a/kotlin-codegen/integration-test/src/test/kotlin/com/squareup/moshi/GeneratedAdaptersTest.kt +++ b/kotlin-codegen/integration-test/src/test/kotlin/com/squareup/moshi/GeneratedAdaptersTest.kt @@ -222,14 +222,16 @@ class GeneratedAdaptersTest { listOf("foo", null, "bar"), setOf("foo", null, "bar"), mapOf("foo" to "bar", "baz" to null), - null + null, + 1 ) val noNullsTypeParams = NullableTypeParams( nullableTypeParams.nullableList, nullableTypeParams.nullableSet, nullableTypeParams.nullableMap.filterValues { it != null }, - null + null, + 1 ) val json = adapter.toJson(nullableTypeParams) @@ -782,7 +784,8 @@ data class NullableTypeParams( val nullableList: List, val nullableSet: Set, val nullableMap: Map, - val nullableT: T? + val nullableT: T?, + val nonNullT: T ) typealias TypeAliasName = String