Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...