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
Scala - Function with Variable Arguments - Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function.
In Scala, use have to indicate that the last argument can be repeated i.e. it can be any variable. The program treats this as an array of that datatype and expects the user to input multiple arguments which can be treated as an array. To show the compiler that this function is going to accept multiple arguments * is used.
Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array [String].
This is Recipe 5.7, “How to Scala create methods that take variable-arguments (varargs) fields.” To make a Scala method more flexible, you want to define a method parameter that can take a variable number of arguments, i.e., a varargs field. Define a varargs field in your method declaration by adding a * character after the field type:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With