nullable & optional/required marks
See original GitHub issueKotlin 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<String> - 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
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
Top GitHub Comments
Ok, but in my case I do not have a default value, and I can not put a random string as a default, because in that case I will not be able to make difference, is it my default or this value was in the request.
So, my solution is
class Req(val foo: Option<String>)
, or value is provided or is missing, null is not allowed.Yes, there is not
Option
class in Kotlin stdlib, but maybe it is possible to add it into this library?