Scala Option 的 isDefined 和 nonEmpty 方法之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22570852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:07:34  来源:igfitidea点击:

Difference between Scala Option's isDefined and nonEmpty method

scala

提问by WoLfPwNeR

In Scala Option, what is the difference between its isDefined and nonEmpty method? Is there any performance difference between the two?

在 Scala Option 中,它的 isDefined 和 nonEmpty 方法有什么区别?两者之间有什么性能差异吗?

回答by Lee

Looking at the source, the definition of nonEmptyis:

看源码,定义nonEmpty是:

final def nonEmpty = isDefined

final def nonEmpty = isDefined

回答by vptheron

They are literally the same. I believe nonEmptyis provided mostly for consistency with the Collection API.

它们实际上是相同的。我相信nonEmpty主要是为了与 Collection API 保持一致而提供的。

回答by som-snytt

You might look at it the other way around.

你可以反过来看。

If Optiondidn't provide nonEmpty, it would be provided through the conversion to an Iterable, which invokes toList.

如果Option没有提供nonEmpty,它将通过转换为 an 提供Iterable,它调用toList.

Do you want to turn your Optioninto a Listjust to check that property? Of course not.

你想把你Option变成一个List只是为了检查那个属性吗?当然不是。

So the issue is not whether nonEmptyis more efficient vis-a-vis isDefined, but vis-a-vis the conversion.

所以问题不在于相对于转换是否nonEmpty更有效isDefined,而是相对于转换。

If it relied on the conversion, it would wind up doing lengthCompare, which creates an iterator as overhead.

如果它依赖于转换,它最终会做lengthCompare,这会创建一个迭代器作为开销。

So the answer is that you may use whichever method you prefer.

所以答案是您可以使用您喜欢的任何方法。

回答by Johnny

From Scala 2.13.xcodebase, it's:

Scala 2.13.x代码库,它是:

def isDefined: Boolean = !isEmpty
...
final def nonEmpty = isDefined

So, logically, no difference between the two.

因此,从逻辑上讲,两者之间没有区别。