Scala: Constructor taking either Seq or varargs

前端 未结 3 1255
鱼传尺愫
鱼传尺愫 2021-01-01 15:43

I am guessing that, for compatibility reasons, the type of vararg parameters Any* is Array[Any] - please correct this if I\'m wrong. However, this does not expl

3条回答
  •  清歌不尽
    2021-01-01 16:20

    A method taking varargs is also always taking a sequence, so there is no need to define an auxiliary constructor or overloaded method.

    Given

    class Api(api_url: String, params: (String, String)*)
    

    you can call it like this

    new Api("url", ("a", "b"), ("c", "d"))
    

    or

    val seq = Seq(("a", "b"), ("c", "d"))
    new Api("url", seq:_*)
    

    Also, in your question, you are calling method seq on the params parameter. This probably does not do what you intended. seq is used to ensure that operations on the resulting collection are executed sequentially instead of in parallel. The method was introduced with the parallel collections in version 2.9.0 of Scala.

    What you probably wanted to use was toSeq, which returns the collection it is used on converted to a Seq (or itself if it is already a Seq). But as varargs parameters are already typed as Seq, that is a no-op anyway.

提交回复
热议问题