22
我有一个叫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.fromNullable(this.line2);
}
// and a Builder
public static class Builder {
// builder methods
}
}
在这里,我不得不写Builder
和Getter
因为,如果我想返回一个可选的同时使用龙目岛,我将有宣布line2
为Optional<String>
。这将产生一个建造者的方法,接受Optional<String>
!
是否有使用龙目岛与Optional
任何其他方式?
我真的很感谢你回答这个问题!谢谢! 我知道这种不使用'可选'作为'null'替换的原理。如果在getter中使用''Optional',它将会过度使用。但是,Google Guava的开发人员还有另一种更方便的理念,它允许您使用Optional来替换null [Guava的可选](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google /common/base/Optional.html) 所以,我个人认为,'lombok' SHLD保持中立,并提供autoOptional支持,并留下是否使用它,或者不给程序员 –
我们总是可以增加新的功能,但我们确实试图首先关注最重要的功能。这在我们看来不是其中之一。我们还没有遇到过这种模式。 –
确实有在领域和getter有可选的参数。它可以成为你使用null的很多地方的一个很好的替代品,但是并不试图模仿isPresent的空检查。 – ymajoros