-
Notifications
You must be signed in to change notification settings - Fork 660
Description
Kotlin solves NullPointerException with nullable/non-nullable classes.
But sometimes we need to show that a field is required or not. Yes sometimes we can express this by using null, but not always.
An use case will be partial update, when we want to update just some columns in database.
So, if a column is nullable in database, we can not send null to that field, because null is valid value for it.
A solution will be to use a class Maybe
or Option
, something like java's Optional
.
The issue with Optional
is that it accepts null even if we have Optional<String>
, it should accept null only if we have Optional<String?>
.
- Option - optional & non-nullable
- Option<String?> - optional & nullable
- String - required & non-nullable
- String? - required & nullable
This mean, or we send a data for the field, or just do not send the field in request, null is not allowed.
{"foo": "bar", "baz": true}
is allowed
{"baz": true}
is allowed, because is optional
{"foo": null, "baz": true}
is NOT allowed, because is non-nullable
Basically null
has the meaning of "this property existed before, and I want to nullify its value". If there's no value, or the value needs not change (for requests, for example), it just shouldn't be sent.
An example of partial update you can find here https://medium.com/workflowgen/graphql-mutations-partial-updates-implementation-bff586bda989
This is also supported by OpenAPI https://swagger.io/docs/specification/data-models/data-types/ you can find that a filed can be marked as optional & non-nullable