When to use Option

后端 未结 4 774
长发绾君心
长发绾君心 2020-12-09 08:40

I learn Scala for some time and can\'t clearly understand the usage of Option. It helps me to avoid null checks when I chain functions (according to docs). That\'s clear for

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 09:21

    The idea behind Options is to get rid off null, so yes, you should use them instead of returning "null or a value". That's also why, if you want to model optional fields (0..1 relationship with other objects), using Option is definitely a good thing.

    The little drawback is that it renders declaration of class with a lot of optional field a bit verbose, as you mentionned.

    One more thing, in scala, you are encouraged to use "immutable objects", so in your example, the fields should be some vals. ;)

提交回复
热议问题