Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature flag to serialize unitialized lateinit properties into null #882

Open
SButterfly opened this issue Jan 14, 2025 · 1 comment
Open

Comments

@SButterfly
Copy link

Use case

We log entity classes before saving them to the database

data class MyEntity(
 val text: String,
... other required properties
) {
lateinit var createAt: Instant // this field is initialized after the entity is saved to the Database
}

fun save(entity: MyEntity) {
  log.info("About to save ${objectMapper.writeValueAsString(entity)}")
  repository.save(entity)
}

Describe the solution you'd like

A new feature flag

    val module = KotlinModule.Builder()
            .configure(KotlinFeature.UnintializedLateInitToNull, true) // to write them as nulls
            .configure(KotlinFeature.UnintializedLateInitToIgnore, true) // or to avoid them
          .build()

Describe alternatives you've considered

No response

Additional context

No response

@k163377
Copy link
Contributor

k163377 commented Jan 25, 2025

It may be possible to achieve this, but needs to be investigated in detail.

First, the lateinit property and its decompiled result are as follows.
You can see that an error is always thrown when the getter is called.

class Dto { lateinit var name: String }
public final class Dto {
   public String name;

   @NotNull
   public final String getName() {
      String var1 = this.name;
      if (var1 != null) {
         return var1;
      } else {
         Intrinsics.throwUninitializedPropertyAccessException("name");
         return null;
      }
   }

   public final void setName(@NotNull String var1) {
      Intrinsics.checkNotNullParameter(var1, "<set-?>");
      this.name = var1;
   }
}

I can think of roughly two ways to make serialization work in this situation.

One is to ignore the getter and use the field for serialization.
The other is to hack the JsonFilter mechanism and display nothing if it is before initialization.

However, the feasibility of both has not been confirmed.
Also, it should be discussed how it should be handled based on consistency with functions such as JsonSetter(nullsUsing = ...).
For now, I feel that the policy of “serialize to undefined if not yet initialized” is the way to go, but I can understand the opinion that it should be serialized as null.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants