Michael Michael - 5 months ago 19
Scala Question

Why is foreach better than get for Scala Options?

Why using

etc. are considered better than using
for Scala Options? If I use
I can call


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

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)

With if, things start to get messy fast.