为什么 foreach 比 get for Scala Options 更好? [英] Why is foreach better than get for Scala Options?

查看:38
本文介绍了为什么 foreach 比 get for Scala Options 更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在 Scala 选项中使用 foreachmapflatMap 等被认为比使用 get 更好?如果我使用isEmpty,我可以安全地调用get.

Why using foreach, map, flatMap etc. are considered better than using get for Scala Options? If I useisEmpty I can call get safely.

推荐答案

嗯,这又回到了告诉,不要问"的问题上.考虑这两行:

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

在第一种情况下,您正在查看 opt 的内部,然后根据您看到的内容做出反应.在第二种情况下,你只是告诉 opt 你想要做什么,让它处理它.

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

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

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).

此外,它是不可组合的.如果您有三个选项,一个用于理解的选项即可解决:

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)

使用 if,事情开始变得很快.

With if, things start to get messy fast.

这篇关于为什么 foreach 比 get for Scala Options 更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆