为什么 foreach 比 get for Scala Options 更好?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6819373/
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 03:15:19  来源:igfitidea点击:

Why is foreach better than get for Scala Options?

scalascala-option

提问by Michael

Why using foreach, map, flatMapetc. are considered better than using getfor Scala Options? If I useisEmptyI can call getsafely.

为什么使用foreachmapflatMap等被认为比使用更好的get斯卡拉选项?如果我使用isEmpty我可以get安全地打电话。

回答by Daniel C. Sobral

Well, it kind of comes back to "tell, don't ask". Consider these two lines:

嗯,它有点回到“告诉,不要问”。考虑这两行:

if (opt.isDefined) println(opt.get)
// versus
opt foreach println

In the first case, you are looking inside optand then reacting depending on what you see. In the second case you are just telling optwhat you want done, and let it deal with it.

在第一种情况下,您正在向内看opt,然后根据所见做出反应。在第二种情况下,你只是告诉opt你想要做什么,让它处理它。

The first case knows too much about Option, replicates logic internal to it, is fragile and prone to errors (it can result in run-time errors, instead of compile-time errors, if written incorrectly).

第一种情况知道太多Option,复制其内部的逻辑,很脆弱并且容易出错(如果编写不正确,它可能导致运行时错误,而不是编译时错误)。

Add to that, it is not composable. If you have three options, a single for comprehension takes care of them:

除此之外,它是不可组合的。如果您有三个选项,一个用于理解的选项可以解决它们:

for {
  op1 <- opt1
  op2 <- opt2
  op3 <- opt3
} println(op1+op2+op3)

With if, things start to get messy fast.

使用if,事情会很快变得混乱。

回答by Dylan

One nice reason to use foreachis parsing something with nested options. If you have something like

使用的一个很好的理由是使用foreach嵌套选项解析某些内容。如果你有类似的东西

val nestedOption = Some(Some(Some(1)))
for {
  opt1 <- nestedOption
  opt2 <- opt1
  opt3 <- opt2
} println(opt3)

The console prints 1. If you extend this to a case where you have a class that optionally stores a reference to something, which in turn stores another reference, for comprehensions allow you to avoid a giant "pyramid" of None/Some checking.

控制台打印1. 如果您将此扩展到您有一个类可以选择存储对某物的引用的情况,该类又存储另一个引用,则理解允许您避免无/一些检查的巨大“金字塔”。

回答by Landei

There are already excellent answers to the actual question, but for more Option-foo you should definitely check out Tony Morris' Option Cheat Sheet.

实际问题已经有了很好的答案,但是对于更多Option-foo,您绝对应该查看Tony Morris 的 Option Cheat Sheet

回答by dhg

The reason it's more useful to apply things like map, foreach, and flatMapdirectly to the Optioninstead of using getand then performing the function is that it works on either SomeorNoneand you don't have to do special checks to make sure the value is there.

将诸如map, foreach, and 之类的东西flatMap直接应用于Option而不是使用get然后执行函数更有用的原因是它适用于SomeorNone并且您不必进行特殊检查以确保该值存在。

val x: Option[Int] = foo()
val y = x.map(_+1) // works fine for None
val z = x.get + 1  // doesn't work if x is None

The result for yhere is an Option[Int], which is desirable since if xis optional, then ymight be undetermined as well. Since getdoesn't work on None, you'd have to do a bunch of extra work to make sure you didn't get any errors; extra work that is done for you by map.

y这里的结果是 an Option[Int],这是可取的,因为 ifx是可选的,那么y也可能是不确定的。由于get在 上不起作用None,您必须做一些额外的工作以确保您没有收到任何错误;由 为您完成的额外工作map

回答by JNM

Put simply:

简单地说:

  • If you need to do something (a procedure when you don't need to capture the return value of each invocation) only if the option is defined (i.e. is a Some): use foreach(if you care about the results of each invocation, use map)

  • If you need to do something if the option defined and something else if it's not: use isDefinedin an if statement

  • If you need the value if the option is a Some, or a default value if it is a None: use getOrElse

  • 如果你需要做某事(当你不需要捕获每次调用的返回值时的一个过程)只有在定义了选项(即是 a Some)时:使用foreach(如果你关心每次调用的结果,使用map

  • 如果您需要在定义了选项的情况下执行某些操作,否则需要执行其他操作:isDefined在 if 语句中使用

  • 如果选项是 a 则需要该值,如果是 a 则需要Some默认值None:使用getOrElse

回答by Balaji Reddy

Trying to perform our Operations with getis more imperative style where u need to tel what to do and how to do. In other words , we are dictating things and digging more into the Optionsinternals. Where as map,flatmapare more functional way of doing things where we are say what to do but not how to do.

尝试以get更命令式的方式执行我们的操作,您 需要告知要做什么以及如何做。换句话说,我们正在口授事物并深入挖掘Options内部结构。哪里 map,flatmap是更实用的做事方式,我们只说要做什么,但不说怎么做