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

前端 未结 7 1305
灰色年华
灰色年华 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 22:43

    I think as long as no language support in Scala for a real kind of void (explanation below) ‘type’, using Option is probably the cleaner solution in the long run. Maybe even for all default parameters.

    The problem is, that people who use your API know that some of your arguments are defaulted might as well handle them as optional. So, they’re declaring them as

    var url: Option[String] = None
    

    It’s all nice and clean and they can just wait and see if they ever get any information to fill this Option.

    When finally calling your API with a defaulted argument, they’ll face a problem.

    // Your API
    case class Gather(url: String) { def this() = { ... } ... }
    
    // Their code
    val gather = url match {
      case Some(u) => Gather(u)
      case _ => Gather()
    }
    

    I think it would be much easier then to do this

    val gather = Gather(url.openOrVoid)
    

    where the *openOrVoid would just be left out in case of None. But this is not possible.

    So you really should think about who is going to use your API and how they are likely to use it. It may well be that your users already use Option to store all variables for the very reason that they know they are optional in the end…

    Defaulted parameters are nice but they also complicate things; especially when there is already an Option type around. I think there is some truth in your second question.

提交回复
热议问题