在Java中有标准的Option或Nullable类吗?

编程入门 行业动态 更新时间:2024-10-17 15:31:45
本文介绍了在Java中有标准的Option或Nullable类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Nullable (C#)有一点不同的含义,但无论如何选项(Scala) $ c> Nullable 可用于表示值或无的概念。

例如,当您想要查找substring在一个字符串中 - 而不是obscure -1作为Int,它会更好的返回Option [Int](在Scala中它将无为无) p>

在标准Java中有这样的类吗?如果是,是什么?

请注意,我不是问如何写这样的类。 更新

正如我写的, Nullable 有不同的含义。考虑这个:

想象一下Map [K,V]和方法get,语义是获得键的值,如果有这样的键,没有这样的密钥。

您不能使用null有两个原因,你不能使用任何具体类的一个原因。选项[V]是要走的路。

解决方案

否。 *

有 FunctionalJava中的选项或者作为yshavit注释,在Guava中可选 ...或者,您可以创建自己的类型,支持...好,让我们说我避免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类吗?

本文发布于:2023-11-02 14:14:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   标准   Java   类吗   Nullable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!