1

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Baha' Al-Khateib
  • 311
  • 3
  • 13

2 Answers2

3

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: _*)
Daniel B.
  • 929
  • 4
  • 8
1

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.

Alok Chaudhary
  • 3,481
  • 1
  • 16
  • 19