Why is foreach better than get for Scala Options?

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

    Put simply:

    • If you need to do something (a procedure when you don't need to capture the return value of each invocation) only if the option is defined (i.e. is a Some): use foreach (if you care about the results of each invocation, use map)

    • If you need to do something if the option defined and something else if it's not: use isDefined in an if statement

    • If you need the value if the option is a Some, or a default value if it is a None: use getOrElse

提交回复
热议问题