Appendix B. Null safety and optionals

B.1 Using null safety

If the language we’re using supports null safety (and we’ve enabled it, should that be required), there will be a mechanism for annotating types to indicate that they can be null. This often involves a ? character to indicate nullability. Code will often look something like the following:

Element? getFifthElement(List<Element> elements) {      
  if (elements.size() < 5) {
    return null;
  }
  return elements[4];
}

The ? in Element? indicates that the return type can be null.

If an engineer using this code forgets to handle the scenario where getFifthElement() returns null, their code will not compile, as demonstrated in the following listing:

void displayElement(Element element) { ... }           

Get Good Code, Bad Code now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.