Why is foreach better than get for Scala Options?

前端 未结 6 423
深忆病人
深忆病人 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条回答
  •  梦毁少年i
    2021-01-31 08:25

    The reason it's more useful to apply things like map, foreach, and flatMap directly to the Option instead of using get and then performing the function is that it works on either Some or None and you don't have to do special checks to make sure the value is there.

    val x: Option[Int] = foo()
    val y = x.map(_+1) // works fine for None
    val z = x.get + 1  // doesn't work if x is None
    

    The result for y here is an Option[Int], which is desirable since if x is optional, then y might be undetermined as well. Since get doesn't work on None, you'd have to do a bunch of extra work to make sure you didn't get any errors; extra work that is done for you by map.

提交回复
热议问题