-4

I'm currently overriding in my repository interface the findById to return a normal object because I don't like the unecessary code I have to do like: .isPresent() and .get()

ApplicationType findById(long applicationTypeId);

I just check if(applicationType != null)

Any reason why Optional is implemented here??

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
user12361681
  • 97
  • 2
  • 7

1 Answers1

3

Optional is implemented in JDK since JDK 8.

It humbly wants to avoid using the checks of null throught the code (just as you actually did)

Optional return here means we can either have an ApplicationType value or null.

When having an Optional you can check the value with isPresent(). The value of Optional can be fetched with get()

Optional are interesting especially when performing action directy with functions on the optinal itself with something alone with this :

Optional<ApplicationType> applicationType = repo.findById(1L);
applicationType.ifPresent(value -> doSomething(value));
applicationType.orElse(defaultApplicationType);

Here a complete guide on Optionals

Hassam Abdelillah
  • 2,246
  • 3
  • 16
  • 37