Reputation: 2989
I have this function:
public static long toEpochMilli(OffsetDateTime dateTime) {
return dateTime.toInstant().toEpochMilli();
}
that I want to use but I have to check before if it is null
private Long buildBookingValidDate (TimeIntervalType validFor) {
return Optional.ofNullable(validFor.getStartTimeStamp())
.ifPresent(DateUtils::toEpochMilli);
}
but I don't know how to return the value
Upvotes: 0
Views: 2083
Reputation: 3134
You are misusing Optional
- it wasn't designed to replace null check.
If you still don't want to use plain, old Java for your case then you can create a helper method like
static <T, R> R applyIfNotNull(T obj, Function<T, R> function) {
return obj != null ? function.apply(obj) : null;
}
and call it as follows
long time = applyIfNotNull(validFor.getStartTimeStamp(), FooBar::toEpochMilli);
and since you like so much Optional
, you can use it in applyIfNotNull
method:
static <T, R> Optional<R> applyIfNotNull(T obj, Function<T, R> function) {
return obj != null ? Optional.of(function.apply(obj)) : Optional.empty();
}
Upvotes: 0
Reputation: 73558
Here's how it would look in "normal" Java. Just for comparison.
private Long buildBookingValidDate (TimeIntervalType validFor) {
if(validFor.getStartTimeStamp() == null)
return null;
return DateUtils.toEpochMilli(validFor.getStartTimeStamp());
}
Upvotes: 2
Reputation: 31222
I will recommend using .map
and return Optional<Long>
instead of null
when input is null
.
example using jshell,
When input is some value,
jshell> import java.time.OffsetDateTime
jshell> Optional<OffsetDateTime> data = Optional.ofNullable(OffsetDateTime.now())
data ==> Optional[2019-09-08T23:36:48.470738-07:00]
jshell> data.map($ -> $.toInstant().toEpochMilli())
$2 ==> Optional[1568011008470]
When input is empty, it will return Optional.empty
but client has to check if the output has value in it
jshell> Optional<OffsetDateTime> data = Optional.ofNullable(null)
data ==> Optional.empty
jshell> data.map($ -> $.toInstant().toEpochMilli())
$4 ==> Optional.empty
Upvotes: 0