Skip to content

Optional field builder should be covariant #8

@JacekLach

Description

@JacekLach

Currently conjure generates builders for optionals like so:

        private Optional<Object> lt = Optional.empty();

        /** Optional exclusive upper bound for the value of the Field. */
        @JsonSetter("lt")
        public Builder lt(Optional<Object> lt) {
            this.lt = Objects.requireNonNull(lt, "lt cannot be null");
            return this;
        }

        /** Optional exclusive upper bound for the value of the Field. */
        public Builder lt(Object lt) {
            this.lt = Optional.of(Objects.requireNonNull(lt, "lt cannot be null"));
            return this;
        }

Since we know optionals are read-only, it's safe to be covariant here:

        private Optional<Object> lt = Optional.empty();

        /** Optional exclusive upper bound for the value of the Field. */
        @JsonSetter("lt")
        public Builder lt(Optional<? extends Object> lt) {
            this.lt = Objects.requireNonNull(lt, "lt cannot be null").flatMap(Optional::<Object>of);
            return this;
        }

        /** Optional exclusive upper bound for the value of the Field. */
        public Builder lt(Object lt) {
            this.lt = Optional.of(Objects.requireNonNull(lt, "lt cannot be null"));
            return this;
        }

which avoids a gotcha for Object specifically (passing Optional<String> into .lt and getting back Optional<Optional<String>>), and makes the interface nicer for all optionals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions