【发布时间】:2020-04-27 22:27:45
【问题描述】:
如果第 3 方在方法中请求参数 attachments,我知道我的参数可能为空,如何避免使用 if 并中断方法链接?该方法的定义如下。
// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);
当附件 == null 时,我更喜欢 NOT 为 .withAttachments 使用 if 条件。我知道 javascript 有方法?(),但是什么适合 java8 或更高版本?在(附件== null)的情况下,我根本不想打电话给.withAttachments()。但是,我没有看到类似 javascript 或 typescript 中的 methodA?() 的语法。
return emailBuilder()
.withSubject(email.getSubject())
.withReplyTo(replyAddresses)
.withAttachments(attachments) // This is conditional...based on attachments
.withHeader("X-showheader", email.getShowHeader());
.build();
我需要这样做吗?
EmailBuilder eb = emailBuilder()
.withSubject(email.getSubject())
.withReplyTo(replyAddresses);
if(attachments)
eb = eb.withAttachments(attachments); // This is conditional...based on attachments
eb = eb.withHeader("X-showheader", email.getHeader())
.build;
return eb;
【问题讨论】:
标签: java optional method-chaining notnull