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 6c806c9..82d886b 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 @@ -71,7 +71,9 @@ internal fun TypeName.asTypeBlock(): CodeBlock { return bound.asTypeBlock() } is ClassName -> { - return when (this) { + // Check against the non-nullable version for equality, but we'll keep the nullability in + // consideration when creating the CodeBlock if needed. + return when (copy(nullable = false)) { BOOLEAN, CHAR, BYTE, SHORT, INT, FLOAT, LONG, DOUBLE -> { if (isNullable) { // Remove nullable but keep the java object type diff --git a/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/DualKotlinTest.kt b/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/DualKotlinTest.kt index 99005b6..8017ed9 100644 --- a/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/DualKotlinTest.kt +++ b/kotlin/tests/src/test/kotlin/com/squareup/moshi/kotlin/DualKotlinTest.kt @@ -435,6 +435,52 @@ class DualKotlinTest(useReflection: Boolean) { val wildcardOut: GenericClass, val complex: GenericClass ) + + // Regression test for https://github.com/square/moshi/issues/991 + @Test fun nullablePrimitiveProperties() { + val adapter = moshi.adapter() + + @Language("JSON") + val testJson = """{"objectType":"value","boolean":true,"byte":3,"char":"a","short":3,"int":3,"long":3,"float":3.2,"double":3.2}""" + + val instance = NullablePrimitives( + objectType = "value", + boolean = true, + byte = 3, + char = 'a', + short = 3, + int = 3, + long = 3, + float = 3.2f, + double = 3.2 + ) + assertThat(adapter.toJson(instance)) + .isEqualTo(testJson) + + val result = adapter.fromJson(testJson)!! + assertThat(result).isEqualTo(instance) + } + + @JsonClass(generateAdapter = true) + data class NullablePrimitives( + val objectType: String = "", + val boolean: Boolean, + val nullableBoolean: Boolean? = null, + val byte: Byte, + val nullableByte: Byte? = null, + val char: Char, + val nullableChar: Char? = null, + val short: Short, + val nullableShort: Short? = null, + val int: Int, + val nullableInt: Int? = null, + val long: Long, + val nullableLong: Long? = null, + val float: Float, + val nullableFloat: Float? = null, + val double: Double, + val nullableDouble: Double? = null + ) } typealias TypeAlias = Int