4

I understand that Optionals ifPresent() call is meant to replace a null check. Pulling code examples from the Oracle documentation, it appears to be very useful in simple situations. For example:

Optional<Soundcard> soundcard = ...;
soundcard.ifPresent(System.out::println);

I just want to understand why this is considered better than a null check. Readability? Performance? It seems to me that this would cause a hit to project performance, as a new object must be introduced in order to hold the object we ultimately wish to obtain? In full, why is this soundcard.ifPresent()

considered better than this if(soundcard != null).

Ivan1211
  • 181
  • 1
  • 7

1 Answers1

4

Optional is a way of replacing a nullable reference with a non-null value. An Optional may either contain a non-null reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

And besides readability it forces you to think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case.

Source: Using and Avoiding null

And as referred before, have a look at this thoroughly answered post.

Community
  • 1
  • 1
x80486
  • 6,627
  • 5
  • 52
  • 111