Why is foreach better than get for Scala Options?

前端 未结 6 420
深忆病人
深忆病人 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:28

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

    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.

提交回复
热议问题