https://kotlinlang.org logo
#jackson-kotlin
Title
# jackson-kotlin
m

mp

09/19/2018, 4:32 PM
Sounds like conflating layers to me… your request has nullable fields; your domain model does not
r

rrader

09/20/2018, 4:30 AM
yes, request has nulls, and I want in response to write that
baz
and
bar
fields are required
But Kotlin throw an execption when pass null to not nullable, so we fail at first field, and can write only about 1 field at once
the desired result will be to write about both fields
d

diesieben07

09/20/2018, 7:31 AM
Non-Nullable types are not for user-input validation. If there is a possibility that
null
can come in from the outside world, the type in kotlin must be nullable. Validation is a separate step.
r

rrader

09/20/2018, 7:35 AM
if field is nullable, I will have to check field if it is not null everytime I want to use it, but it was already validated at some step
d

diesieben07

09/20/2018, 8:38 AM
Yes, unfortunately Kotlin's type system is not as rich as e.g. TypeScript's. That would allow you express something like that
The way to do it would be to have two versions of your data classes, one that is not validated and one that is validated. Then you can also introduce domain classes like
Email
.
r

rrader

09/20/2018, 8:43 AM
Do you have an example of TypeScript in such cases?
I don't want 2 classes, why is it not ok to disable null checks in this only for module with such classes, in these classes validation is done by framework and will guarantee that fields will not be null
d

diesieben07

09/20/2018, 8:59 AM
Typescript example:
Copy code
type Foo<T> = {
    baz: string | T
    bar: number | T
}

type FooUnvalidated = Foo<null>
type FooValidated = Foo<never>

function validate(input: FooUnvalidated): FooValidated {
    const {baz, bar} = input;
    if (baz === null) throw Error();
    if (bar === null) throw Error();
    return {
        baz, bar
    }
}

const input: FooUnvalidated = {baz: null, bar: 123};
const validated = validate(input);
const bar: number = validated.bar;
const doesntWork: number = input.bar; // does not compile, input.bar could be null
9 Views