Simplify if (x) Some(y) else None?

后端 未结 7 1898
旧时难觅i
旧时难觅i 2021-02-05 02:46

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

I was thinking of using a function to simplify:



        
相关标签:
7条回答
  • 2021-02-05 03:27

    Starting Scala 2.13, Option is now provided with the when builder which does just that:

    Option.when(condition)(result)
    

    For instance:

    Option.when(true)(45)
    // Option[Int] = Some(45)
    Option.when(false)(45)
    // Option[Int] = None
    

    Also note the coupled unless method which does the opposite.

    0 讨论(0)
提交回复
热议问题