问题描述
Nullable
(C#)有一点不同的含义,但无论如何选项
(Scala) $ c> Nullable 可用于表示值或无的概念。
例如,当您想要查找substring在一个字符串中 - 而不是obscure -1作为Int,它会更好的返回Option [Int](在Scala中它将无
为无) p>
在标准Java中有这样的类吗?如果是,是什么?
请注意,我不是问如何写这样的类。
更新
正如我写的, Nullable
有不同的含义。考虑这个:
想象一下Map [K,V]和方法get,语义是获得键的值,如果有这样的键,没有这样的密钥。
您不能使用null有两个原因,你不能使用任何具体类的一个原因。选项[V]是要走的路。
否。 *
有或者作为yshavit注释, ...或者,您可以创建自己的类型,支持...好,让我们说我避免Java; - )
快乐编码。
*我不同意 Integer
或 Double
固定的基元集合,不是一个通用的容器。它们可以被认为涵盖了 Nullable
的情况,这仅仅是因为Java的固定值集类型和C#的限制 Nullable
(仅适用于ValueTypes),但是他们不会替换真实的选项
类型。
但请注意,来自FJ或Guava的选项
仍然使用(实际上必须)包装类型(例如 Integer
)用于处理基元。还要注意,由于上述限制,C#中的 Nullable
与Scala中的选项
不同。
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.
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.
这篇关于在Java中有标准的Option或Nullable类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!