Is there a standard Option or Nullable class in Java?

Nullable (C #) has a slightly different meaning, but in either case, both the Option (Scala) and Nullable expressions can be used to express the concept of "value or nothing."

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

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

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

Update

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

Imagine that Map [K, V] and the method get semantics to get the key value if there is such a key or nothing when there is no such key.

You cannot use null for two reasons, you cannot use any particular class for one reason. Option [V] is the path.

+6
source share
3 answers

Not. There is no such constructive standard in Java. *

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

Happy coding.


* I do not agree that Integer or Double fulfill this role, since they only complete a fixed set of primitives and are not a common container. They can be thought of as covering the Nullable case, simply because of the fixed set of Java type values ​​and the C # Nullable restriction (only works with ValueTypes), but they do not replace the actual Option type.

Remember, however, that Option from FJ or Guava still uses (in fact should) wrapper types (e.g. Integer ) to handle primitives. Also note that Nullable in C # does not match Option in Scala due to the above limitation.

+2
source

In Java, the usual way you did this would be with null and Integer , Long , etc. classes (which are equivalents of a reference type for primitive types int , Long , etc., being reference types, references can be null ). If you have a C # background, Integer in Java (with autoboxing) is kind of like int? in c #.

For example, List#indexOf has this signature:

 int indexOf(Object o) 

... and does -1 thing you are talking about. If you designed List and preferred null , you could define it as:

 Integer indexOf(Object o) 

... and returned null , not -1 in the case of "not found".

There are versions of the reference type of all primitive types in Java, and, of course, all other types are already reference types, so you already have the null option.

+5
source

You requested more than two years ago, but two months ago Java SE 8 introduced java.util.Optional<T> . For the opening remarks, see this β€œTechnique” article:

Tired of Null Pointer Exceptions? Consider using Java SE 8 Optional!

+4
source

Source: https://habr.com/ru/post/911353/


All Articles