java 在龙目岛可选
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31670785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Optional in Lombok
提问by Dhrumil Upadhyaya
I have a class called Addresswhich looks like this:
我有一个叫做的类Address,它看起来像这样:
@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 Builderand a Getterbecause, if I want to return an Optional while using Lombok, I will have to declare line2as Optional<String>. And that will generate a builder method which accepts Optional<String>!
在这里我不得不写Builder和 aGetter因为,如果我想在使用 Lombok 时返回一个 Optional,我将不得不声明line2为Optional<String>. 这将生成一个接受Optional<String>!
Is there any other way to use lombok with Optional?
有没有其他方法可以使用 lombok Optional?
采纳答案by Roel Spilker
The answer is no, and it probably never will.
答案是否定的,而且可能永远不会。
You're probably doing it wrong :-) Optionalis not a replacement for nullnor 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.
您可能做错了 :-)Optional不是替代品,null也不是防止NullPointerException. 表示这个问题是无法回答的,比如:一个空的人名单的平均年龄是多少。
Optionals should never be passed on, but unboxed by the calling code as soon as possible.
Optionals 不应该被传递,而是尽快被调用代码拆箱。
See also https://www.voxxed.com/blog/2015/01/embracing-void-6-refined-tricks-dealing-nulls-java/
另见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.
由于这些场景只是少数,而且 Lombok 喜欢让程序员编写更好的代码,我不希望 Lombok 会支持它。
Disclosure: I am a Lombok developer.
披露:我是龙目岛的开发人员。

