Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional in Lombok

I have a class called Address which looks like this:

@Value class Address {     @NotNull String userId;    @NotNull String line1;    String line2;     private Address(Builder b) {       // copy everything from builder    }     // override getter for line2 so that it returns Optional<String>    public Optional<String> getLine2() {       return Optional.ofNullable(this.line2);    }     // and a Builder    public static class Builder {      // builder methods    } } 

Here I am forced to write Builder and a Getter because, if I want to return an Optional while using Lombok, I will have to declare line2 as Optional<String>. And that will generate a builder method which accepts Optional<String>!

Is there any other way to use lombok with Optional?

like image 828
Dhrumil Upadhyaya Avatar asked Jul 28 '15 08:07

Dhrumil Upadhyaya


People also ask

What is the use of optional ()?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

What is Java optional of?

Optional of() method in Java with examples Parameters: This method accepts value as parameter of type T to create an Optional instance with this value. Return value: This method returns an instance of this Optional class with the specified value of the specified type.

Why optional should not be used for fields?

You should almost never use it as a field of something or a method parameter. So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.

Does Optional get return null?

There is no special magic for Optional - it's a class like any other. That means the default value for Optional references (like all references) is null.


1 Answers

The answer is no, and it probably never will.

You're probably doing it wrong :-) Optional is not a replacement for null nor a fancy way to prevent NullPointerException. It is to indicate that the question is unanswerable, like: what is the average age of an empty list of persons.

Optionals should never be passed on, but unboxed by the calling code as soon as possible.

See also https://www.voxxed.com/blog/2015/01/embracing-void-6-refined-tricks-dealing-nulls-java/

Since these scenarios are just a handful, and Lombok likes to enable programmers to write better code, I don't expect there will ever be support for it in Lombok.

Disclosure: I am a Lombok developer.

like image 188
Roel Spilker Avatar answered Sep 22 '22 18:09

Roel Spilker