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.
In Java, the usual way you'd do that would be with
null
and theInteger
,Long
, etc. classes (which are the reference type equivalents of theint
,long
, etc. primitive types; being reference types, the references can benull
). If you have a C# background,Integer
in Java (with autoboxing) is kind of likeint?
in C#.For instance,
List#indexOf
has this signature:...and does the
-1
thing you're talking about. If you were designingList
and preferrednull
, you might have defined it as:...and returned
null
rather than-1
in the "not found" case.There are these reference type versions of all of the primitive types in Java, and of course, all other types are already reference types so you already have the
null
option.You asked more than two years ago, but two months ago, Java SE 8 has introduced
java.util.Optional<T>
. For an intro, see this Technet article:Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
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
orDouble
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 ofNullable
, simply due to Java's fixed set of value types and C#'s limitation ofNullable
(only works on ValueTypes), but they do not replace a realOption
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 thatNullable
in C# is not the same asOption
in Scala due to the aforementioned restriction.