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

shmosel
  • 49,289
  • 6
  • 73
  • 138
User_KS
  • 47
  • 4
  • 5
    if you have `mySeq` which is `Seq[String]`, then you can pass it to a method expecting a `String*` like this: `foo(mySeq: _*)` – Seth Tisue Oct 03 '18 at 20:23
  • Oh wow that worked! But why did that work? Are you casting it when you use it in foo()? – User_KS Oct 03 '18 at 20:48

1 Answers1

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
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Yes but why does this work? What does :_* actually do – User_KS Oct 03 '18 at 22:02
  • 2
    @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: _*."](https://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html). It's just a rarely used syntax that you have to either memorize, or google under "varargs" next time. – Andrey Tyukin Oct 03 '18 at 22:10
  • 1
    @Kian https://stackoverflow.com/questions/6051302/what-does-colon-underscore-star-do-in-scala – Brian McCutchon Oct 03 '18 at 22:15