Why is foreach better than get for Scala Options?

前端 未结 6 428
深忆病人
深忆病人 2021-01-31 07:31

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

6条回答
  •  心在旅途
    2021-01-31 08:35

    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.

提交回复
热议问题