

To get started, let me quote this (retrieved from the Official Java 8 documentation:Ī wise man once said you are not a real Java programmer until you have dealt with a null pointer exception, which is the source of many problems because it is often used to denote the absence of a value.Īlthough this statement is true and Java 8 documentation refers to the use of Optional as NullPointerException saver, in my opinion, it is not only useful to minimize the impact of NPE, but to create more meaningful and readable APIs.Īdditionally, it is well known that not being careful when using null values can lead to a variety of bugs, and for instance, null is ambiguos, and we do not always have a clear meaning for it: is it an inexistent value? For example, when a Map.get() method returns null, can mean the value is absent or the value is present and null. With that being said, in this article, I want to explain what Optional is, expose a few use case scenarios, compare different alternatives (in other languages) and finally, I do want to show you how we can effectively make use of the ( inexistent till now) Optional API on Android (although this can be applied to any Java/Kotlin project, specially those ones targeting Java 7 and above). Java 8, Scala, Groovy and Kotlin Optional/Option APIsįirst of all, this is not a new topic and a lot has already been discussed about it.“A clever person SOLVES a problem, a wise person AVOIDS it.” Optional values are very useful but unfortunately not available in Android (Java and Kotlin Standard Library) so in this post we will see how we can make use of them presenting different practical use case scenarios.
