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

前端 未结 7 1295
灰色年华
灰色年华 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

    Don't auto-convert anything to an Option. Using my answer here, I think you can do this nicely but in a typesafe way.

    sealed trait NumDigits { /* behaviour interface */ }
    sealed trait FallbackUrl { /* behaviour interface */ }
    case object NoNumDigits extends NumDigits { /* behaviour impl */ }
    case object NofallbackUrl extends FallbackUrl { /* behaviour impl */ }
    
    implicit def int2numd(i : Int) = new NumDigits { /* behaviour impl */ }
    implicit def str2fallback(s : String) = new FallbackUrl { /* behaviour impl */ }
    
    class Gather(finishOnKey: Char = '#', 
                  numDigits: NumDigits = NoNumDigits, // Infinite
                  fallbackUrl: FallbackUrl = NoFallbackUrl, 
                  timeout: Int = 5
    

    Then you can call it as you wanted to - obviously adding your behaviour methods to FallbackUrl and NumDigits as appropriate. The main negative here is that it is a ton of boilerplate

    Gather(numDigits = 4, fallbackUrl = "http://wibble.org")
    

提交回复
热议问题