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.
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.
Nullability in Java and Kotlin Nullability is the ability of a variable to hold a null value. When a variable contains null , an attempt to dereference the variable leads to a NullPointerException . There are many ways to write code in order to minimize the probability of receiving null pointer exceptions.
null is not a class.
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.
In Java, the usual way you'd do that would be with null
and the Integer
, Long
, etc. classes (which are the reference type equivalents of the int
, long
, etc. primitive types; being reference types, the references can be null
). If you have a C# background, Integer
in Java (with autoboxing) is kind of like int?
in C#.
For instance, List#indexOf
has this signature:
int indexOf(Object o)
...and does the -1
thing you're talking about. If you were designing List
and preferred null
, you might have defined it as:
Integer indexOf(Object o)
...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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With