为什么 foreach 比 get for Scala Options 更好?
为什么在 Scala 选项中使用 foreach
、map
、flatMap
等被认为比使用 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.