The Optional type in Google Guava

Hi folks ! There was some time ago when I was actively blogging (half of the year or so), so I felt a bit ashamed and decided to write about something interesting. As you probably know I’m working now as a Java developer. Because I’m not a big fan of Java (actually I do hate it) I look from time to time for solutions to over-go Java’s shortcomings.

One of more obvious shortcomings of Java (an many other languages) is the presence of the “null” type. I think that everyone of us has experienced some nasty NullPointerExceptions(NPE) problems. The main case with NPE’s is that in legacy code we often don’t know if the null is a legal value or not. Should it be set or not ?

But fear not my friends! Google has it’s outstanding Guava (former Google Collections) library which has the solution for our problems. This solution is the Optional class. Some of you familiar with functional programming may think now about the Maybe type in Haskell or the Option type in Scala. Guava’s Optional class has some resemblance to these types, but it is not a direct equivalent of the former.

How to use it ?

Could not embed GitHub Gist 4025014: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

This is the basic use of the Optional class. We initialize the variable with the Optional.absent(), if we want to set it, we call Optional.of(someValue). To check if the value is set we may use the isPresent() method of the Optional class. To get the value, just call the get() method.

I could have ended this post now, but the Optional class has some other fancy methods, which I urge you to try ! So here we go:

1. Providing a default value:

Could not embed GitHub Gist 4025093: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

We can use the “or(defaultValue)” method to provide a default value for a variable when the variable is not present.

2. Executing some code if the value is present

Could not embed GitHub Gist 4025133: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

The code in the function passed to the transform method will only by executed if the value is present.

That’s all for now. The Guava library has many other interesting things in it, which I hope to cover in the future. In the mean time use Optional and avoid those nasty NPE’s forever :)

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.