Scala variable arguments: _ *

can anyone bring more shedding on the next chunk of scala code that I'm not quite clear about? I have the following function

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

      

Then I try to pass a list of variable arguments to this function like this:

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

      

First, the snippet ids(adIds)

does not work, which is odd at first, as the error message says: Mismatch type expected: String, actual: Seq [String]. This means that variable argument lists are not typed as collections or sequences.

Use a trick to fix this ids(adIds: _*)

.

I'm not 100% sure how: _ * works, can someone put some shed on it? If I remember correctly: means the operation is applied to the correct argument instead of on the left, _ means "apply" to the passed item, ... I checked the String and Sequence scaladoc but couldn't find: _ * method.

Can anyone explain this?

thank

+3


source to share


1 answer


You should look at your method definitions:

def ids(ids: String*)

      

Here you say that this method accepts a variable number of lines, for example:

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

      



Then the second method:

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

      

This also accepts a variable number of lines that are packed into Seq[String]

, so adIds

it actually is Seq

, but your first method ids

doesn't Seq

, it takes N

, so it ids(adIds: _*)

works.

: _*

this is called the splat operator , which is what the markup of strings does Seq

in N

.

+6


source







All Articles