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

[Possible duplicate] Small inconsistency in the logic of encoding of fields with defaults #2735

Closed
orchestr7 opened this issue Jul 1, 2024 · 1 comment
Labels

Comments

@orchestr7
Copy link
Contributor

orchestr7 commented Jul 1, 2024

(!) I am aware of the encoding of defaults and understand that they are not encoded by default: Encoding Defaults Documentation.

Please close this issue as a duplicate with a reference to the original one, if it exists.

Consider the following scenario where I have a default value for my field b:

@Serializable
data class A(
    val a: String?,
    val b: String = "b"
)

If I pass a different value explicitly:

val value = A("a", "b1")
Json.encodeToString(value)

The encoded output is as expected:

{ "a": "a", "b": "b1" }

However, if I pass the default value explicitly:

val value = A("a", "b")
Json.encodeToString(value)

The encoded output is not what you might expect:

{ "a": "a" }

My team encountered a production error because they did not check if the default compile-time value was equal to the non-default runtime value, and they expected this field to be serialized.

The motivation behind this behavior is clear: it is challenging to distinguish between the default value and an explicitly set value at the frontend level. However, it would be beneficial to mention this explicitly in the README.

@sandwwraith
Copy link
Member

There's no way to distinguish between these two "b"s. In the same way, you can't distinguish between these calls in Kotlin:

fun foo(b: String = "b") {
// you can't tell if "b" is a default value or not
}


foo()
foo("b") // identical call

Actually, the very purpose of default values is to be indistinguishable from user-passed ones. Consider using nulls or wrappers if you need a special differentiation.

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

No branches or pull requests

2 participants