I have been working on some scala code and I have faced _*
used after the arrays like the following (args: _*
).
Can someone tell me its meaning?
I have been working on some scala code and I have faced _*
used after the arrays like the following (args: _*
).
Can someone tell me its meaning?
You can define a function that takes a variable number of arguments, like:
def print(args: String*) {
elements.foreach(println)
}
You can call this with multiple parameters:
print("a")
print("a","b")
Or if you have a sequence, you can call it with a list, but in this case you need to use the _* syntax to splat the sequence instead of passing it as a single parameter
val l = List("a","b")
print(l: _*)
As per the scala documentation this means vararg expansion. other symbols
Vararg in Java was added in java 1.5 so that it can be utilized when the number of parameters to a method are not known.
Some important points about vararg: - Anonymous array is created every time a method is called, which increases the time complexity. So in case when method call results in 1 or 2 parameter most of the time then prefer overloading rather than using vararg.