Are Options and named default arguments like oil and water in a Scala API?

前端 未结 7 1288
灰色年华
灰色年华 2020-12-12 22:30

I\'m working on a Scala API (for Twilio, by the way) where operations have a pretty large amount of parameters and many of these have sensible default values. To reduce typi

相关标签:
7条回答
  • 2020-12-12 23:05

    Personally, I think using 'null' as default value is perfectly OK here. Using Option instead of null is when you want to convey to your clients that something may not be defined. So a return value may be declared Option[...], or a method arguments for abstract methods. This saves the client from reading documentation or, more likely, get NPEs because of not realizing something may be null.

    In your case, you are aware that a null may be there. And if you like Option's methods just do val optionalFallbackUrl = Option(fallbackUrl) at the start of the method.

    However, this approach only works for types of AnyRef. If you want to use the same technique for any kind of argument (without resulting to Integer.MAX_VALUE as replacement for null), then I guess you should go with one of the other answers

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