markdown guide
 

Suppose you have a labeled box which can hold anything you like. On the label you write that the box may or may not be empty, along with what kind of thing you will put in the box (like coffee cup).

You can then give this box to other people and they know that the box very well could be empty or it could contain a coffee cup. Therefore they need to prepare for the case where the box is full and for when the box is empty.

People can always check if the box is empty, pull the coffee cup from the box, do something with the coffee cup in the box but keep it in the box, etc.

  • Box: Optional<T> (also called Option in other langs like Scala)
  • Coffee cup: Object contained in Optional of type T
  • Box label: type signature
  • Giving the box to other people: returning object of type Optional<T>
  • Check if box is empty: Optional::isPresent
  • Pull the coffee cup from the box: Optional::get
  • Do something with the coffee cup in the box: Optional::map

Optionals are a handy explicit way of representing values which may or may not be present (basically it is meant to replace returning null)

 

other Optional methods

Optional::orElse - you have another cup which you will use if the box is empty (or you don't have a cup but act like you do)
Optional::orElseGet - you don't have another cup but you know where to get it (and you throw a fit if you don't get a cup there)
Optional::filter - you only need coffee if it has no sugar
Optional::map - you have a kettle and want to make a cup of coffee
Optional::flatMap - you have a kettle and want to make a cup of coffee but there might be no cups in the cupboard
Optional::ifPresent - do something with a cup

 

Nicely done, Evan!

Thanks for sharing your thoughts :)

 

What value is it adding?
I can do a null/empty check on any object and use it.
Here also I need to check if optional is empty.

Classic DEV Post from Jul 30

Save the planet, clean your mailbox

Christian Vasquez profile image