Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm wondering what the use is of the asterisk (*) symbol in this syntax? I'm obviously new to Scala. I googled but am probably googling the wrong thing. Any help is appreciated.
Cheers!
–
Its called as "var args" (variable arguments).
def concat(strs: String*): String = strs.foldLeft("")(_ ++ _)
Scala REPL
scala> def concat(strs: String*): String = strs.foldLeft("")(_ ++ _)
concat: (strs: String*)String
scala> concat()
res6: String = ""
scala> concat("foo")
res7: String = foo
scala> concat("foo", " ", "bar")
res8: String = foo bar
–
–
–
This is called a repeated parameter (see Section 4.6.3 of the Scala Language Specification).
Repeated Parameters allow a method to take an unspecified number of arguments of the same type T
, which are accessible inside the method body bound to a parameter of type Seq[T]
.
In your case, inside the method m
, the parameter a
will be bound to a Seq[String]
.
That's the syntax to define a method that take a variable number of arguments.
Your m
method can take 0, 1 or more arguments and these are all valid invocations:
m("hello")
m("hello", "world")
You can also pass a collection to that method if you use the appropriate type hint:
val words = Seq("hello", "world")
m(words: _*)
You can play around with this code here on Scastie (where I implemented m
as the concatenation of the input strings).
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.