scalascala-collections

scala variable arguments :_*


could someone bring more shed on following piece of scala code which is not fully clear to me? I have following function defined

  def ids(ids: String*) = {
    _builder.ids(ids: _*)
    this
  }

Then I am trying to pass variable argument list to this function as follows:

def searchIds(kind: KindOfThing, adIds:String*) = {
...
ids(adIds)
}

Firstly, ids(adIds) piece doesn't work which is a bit odd at first as error message says: Type mismatch, expected: String, actual: Seq[String]. This means that variable arguments lists are not typed as collections or sequences.

In order to fix this use the trick ids(adIds: _*).

I am not 100% sure how :_* works, could someone put some shed on it? If I remember correctly : means that operation is applied to right argument instead to left, _ means "apply" to passed element, ... I checked String and Sequence scaladoc but wasn't able to find :_* method.

Could someone explain this?

Thx


Solution

  • You should look at your method definitions:

    def ids(ids: String*)
    

    Here you're saying that this method takes a variable number of strings, eg:

    def ids(id1: String, id2: String, id3: String, ...)
    

    Then the second method:

    def searchIds(kind: KindOfThing, adIds:String*)
    

    This also takes a variable number of string, which are packaged into a Seq[String], so adIds is actually a Seq, but your first method ids doesn't take a Seq, it takes N strings, that's why ids(adIds: _*) works.

    : _* this is called the splat operator, what that's doing is splatting the Seq into N strings.