If a 3rd party requests an argument attachments
in a method, how may I avoid using an if
and break method chaining, knowing that my argument may be null? The method has the following definition.
// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);
I would prefer NOT using an if condition for .withAttachments, when attachments == null. I know that javascript has method?(), but what is appropriate for java8, or above? In the case where (attachments == null), I don't want to call .withAttachments()
at all. But, I don't see syntax comparable to methodA?() like in javascript, or typescript.
return emailBuilder()
.withSubject(email.getSubject())
.withReplyTo(replyAddresses)
.withAttachments(attachments) // This is conditional...based on attachments
.withHeader("X-showheader", email.getShowHeader());
.build();
Would I be required to do this?
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;
Optional
, use a ternary operator:.withAttachments(attachments != null ? attachments : Collections.emptyList())
, though you might have to hint it usingCollections.<Attachment>emptyList()
– Lonergan