Is there standard Option or Nullable class in Java

2019-04-28 23:50发布

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.

3条回答
仙女界的扛把子
2楼-- · 2019-04-29 00:13

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.

查看更多
倾城 Initia
3楼-- · 2019-04-29 00:13

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!

查看更多
看我几分像从前
4楼-- · 2019-04-29 00:14

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.

查看更多
登录 后发表回答