Skip to content

[BUG][Kotlin] models properties order change when they become optional's #4705

@4brunu

Description

@4brunu

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • What's the version of OpenAPI Generator used?
  • Have you search for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Bounty to sponsor the fix (example)
Description

The order of the parameters in a model in kotlin changes if a property changes from required to optional.
This caused issues in my project.

Imagine that you have the class Person and every parameter is required.

// This is the generated class
data class Person (
    val firstName: kotlin.String,
    val lastName: kotlin.String
)

// And this is how you instantiate the class Person
val person = Person("John", "Smith")

This works great, but know the open api spec created by the backend person changes and firstName is now optional.
Now the parameter order changed, and the values are assigned to the wrong property, unless you change all the places in your project where you instantiate this class.

// This is the new generated class
data class Person (
    val lastName: kotlin.String,
    val firstName: kotlin.String? = null
)

// But here you are passing "John" as lastName and "Smith" as firstName
val person = Person("John", "Smith")
openapi-generator version

4.2.2

OpenAPI declaration file content or url

// First example, all properties required
https://gist.github.com/4brunu/e8c82fdcd79dbd3546632bae743138cf

// Second example, one property required
https://gist.github.com/4brunu/85487ad068597658f3b831c5f588faeb

Command line used for generation

openapi-generator generate --input-spec openapi/openapi.json --generator-name kotlin --output openapi/

Steps to reproduce

Run the generated with the two spec files and check the diferences.

Related issues/PRs

None.

Suggest a fix

Keep the order of the parameters despite them being required or not.
Or if it's better for the current behaviour to be keept for backwards compatibility, add an option to keep the order of the model properties.
Something like this

cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));

The Swift 4 generator already has the behaviour of keeping the same order of the parameters, despite of them being required or not.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions