Search code examples
javaclassoption-type

Is there standard Option or Nullable class in Java?


Nullable (C#) has a bit different meaning, but anyway both Option (Scala) and Nullable can be used to express the notion of "value or nothing".

For example in case when you would like to find substring in a string -- instead of obscure -1 as Int, it would be better to return Option[Int] (in Scala it would be None for nothing).

Is there such class in standard Java? If yes, what it is?

Please note, I am not asking how to write such class.

Update

As I wrote, Nullable has different meaning. Consider this:

Just imagine Map[K,V], and method get which semantics is to get value of key, if there is such key, or nothing when there is no such key.

You cannot use null for two reasons, you cannot use any concrete class for one reason. Option[V] is the way to go.


Solution

  • No. There is no such construct standard in Java.*

    There is Option in FunctionalJava or, as yshavit notes, Optional in Guava... Or, you could create your own type... but without proper language support... well, let's just say I avoid Java ;-)

    Happy coding.


    *I disagree that Integer or Double fulfill this role as they only wrap the fixed set of primitives and are not a generic container. They can be considered to cover the case of Nullable, simply due to Java's fixed set of value types and C#'s limitation of Nullable (only works on ValueTypes), but they do not replace a real Option type.

    Do note however, that the Option from FJ or Guava still uses (it must, actually) the wrapper types (e.g. Integer) for handling primitives. Also note that Nullable in C# is not the same as Option in Scala due to the aforementioned restriction.