ansman/kotshi

2.10.0 KSP generates non-compilable classes when nullable field with same name as class and default value

daviddenton opened this issue · 4 comments

If you have a class where:

  • the field name is the same as its class
    AND
  • the field is nullable
    AND
  • the field has a default value

... the KSP generated class does not compile. Try this and you can see:

@JsonSerializable
data class MyClazz(
    val Int: Int? = null
)

So what is happening is that Kotshi internally matches the variable names to your property names. It then gets confused because the there is both a type and a variable with the same name.

Although this can be fixed, I would highly recommend that your type names to start with an upper case and your property names start with a lower case letter as this can cause all kinds of issues.
You can use the JsonProperty annotation to change the name of the serialized value:

@JsonSerializable
data class MyClazz(
    @JsonProperty(name = "Int")
    val int: Int? = null
)

Agreed. We would normally definitely name the parameters normally with lowercase. The issue is that we're building this for an OSS library - http4k-connect, which uses Kotshi to generate the adapters for a bunch of services, including AWS:

The structure of the Amazon JSON looks like this - where the name of the fields starts with an Upper-case. The naming of the classes in the lib is identical to the name of the field (the objects were generated by computer):

{
   "AddReplicaRegions": [ 
      { 
         "KmsKeyId": "string",
         "Region": "string"
      }
   ],
   "ClientRequestToken": "string",
   "Description": "string",
   "ForceOverwriteReplicaSecret": boolean,
   "KmsKeyId": "string",
   "Name": "string",
   "SecretBinary": blob,
   "SecretString": "string",
   "Tags": [ 
      { 
         "Key": "string",
         "Value": "string"
      }
   ]
}

We get that this would be a change, but it is inconsistent with the Kapt generators and more people might come across the same issue in the future (causing you the maintainer more headaches 😉 ). It's your call obvs - I can submit a patch if you will accept it and feel like you're too busy 😄 .

I've added a fix and will release it soon. It doesn't technically fix all cases, it can still happen if your type is lower case but there really isn't an easy way to fix this.

It's definitely up to you but personally I would generate your data classes with lower cased names (you'd have to have some logic here anyway in case the key has a space or - in it for example) and add @JsonProperty, but that's again up to you of course.

2.10.1 has been released containing the fix