Java Options Class

https://www.youtube.com/watch?v=vKVzRbsMnTQ

  • All Optional is a container , that either has something in it or it doesn't
  • example : if you query something by name in DB it may or may not return something










think of it as a box with a label.





















  • if cat found in DB , then it fills Optional with that data
  • if cat not found in DB then it it puts a null in optional to return Empty "Optional"
if you know for sure that thing you will put inside Optional is never null use OF instead , if null goes in below code exception is thrown




The way you return is above






Although end result is similar to first , but when user sees Optional it knows that it can expect it to be blank.


There is also
  • orElseGet( ) : use a lambda to create unknown cat
  • orElseThrow( ) : if optional is empty throw "noSuchElementException" ( similar to get( ) ) 
Get Age or else return 0





NOTE
  • Optional is only meant to be used as a return type and nothing else
  • do not overuse it









Comments

Popular posts from this blog

Agentic AI Course : Week 1

LLM Engineering course : Day 1

LLM Engineering : Week 2