Is there a way to declare a variable of type String* in scala? As in a variable number of arguments? The issue is that when I want to test a series of methods that takes in a String* as a parameter and don't want to just replicate the values I pass in every test. I know that I can change the functions to take in a collection of String like Array or Seq, but I wanted to know if there was a way to do it without changing the parameter types
1 Answer
Varargs notation:
def foo(ss :String*) = {
//ss is Seq[String], you can ss.map(), ss.length, etc.
}
usage:
foo()
foo("this", "that")
foo("abc", "abd", "abx")
val someList = List("another" , "collection", "of", "strings")
foo(someList :_*) // turn a collection into individual varargs parameters
3 Comments
User_KS
Yes but why does this work? What does :_* actually do
Andrey Tyukin
@KianShahangyan It's just a marker that tells the compiler to treat an argument as vararg. It has no other meaning anywhere else. Quote: "The last argument in an application may be marked as a sequence argument, e.g. e: _*.". It's just a rarely used syntax that you have to either memorize, or google under "varargs" next time.
Brian McCutchon
mySeqwhich isSeq[String], then you can pass it to a method expecting aString*like this:foo(mySeq: _*)