0

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

2
  • 5
    if you have mySeq which is Seq[String], then you can pass it to a method expecting a String* like this: foo(mySeq: _*) Commented Oct 3, 2018 at 20:23
  • Oh wow that worked! But why did that work? Are you casting it when you use it in foo()? Commented Oct 3, 2018 at 20:48

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Yes but why does this work? What does :_* actually do
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.