Skip to content

Commit

Permalink
fix(kt): optional fields now default to null (#688)
Browse files Browse the repository at this point in the history
Before:

```kotlin
data class Foo(
  val bar: String?,
)
```

After:

```kotlin
data class Foo(
  val bar: String? = null
)
```
  • Loading branch information
alecthomas authored Dec 1, 2023
1 parent 259799f commit 338989b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@ class ModuleGenerator() {
type.fields.forEach { field ->
dataClassBuilder.addKdoc(field.comments.joinToString("\n"))
field.type?.let {
dataConstructorBuilder.addParameter(field.name, getTypeClass(it, namespace))
var parameter = ParameterSpec
.builder(field.name, getTypeClass(it, namespace))
if (it.optional != null) {
parameter = parameter.defaultValue("null")
}
dataConstructorBuilder.addParameter(parameter.build())
dataClassBuilder.addProperty(
PropertySpec.builder(field.name, getTypeClass(it, namespace)).initializer(field.name).build()
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public data class TestResponse(
public val string: String,
public val bool: Boolean,
public val time: OffsetDateTime,
public val optional: String?,
public val optional: String? = null,
public val array: ArrayList<String>,
public val nestedArray: ArrayList<ArrayList<String>>,
public val dataRefArray: ArrayList<TestRequest>,
Expand Down

0 comments on commit 338989b

Please sign in to comment.