Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there standard Option or Nullable class in Java?

Tags:

java

class

option

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.

like image 603
greenoldman Avatar asked Mar 21 '12 20:03

greenoldman


People also ask

Does Java have nullable?

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.

Does Java have null class?

null is not a class.

Are ints nullable in Java?

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.

Are C# classes Nullable?

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.


2 Answers

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.

like image 197
T.J. Crowder Avatar answered Nov 15 '22 00:11

T.J. Crowder


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!

like image 20
Lumi Avatar answered Nov 15 '22 01:11

Lumi