Search code examples
scalascala-3

Is there a syntax for varargs splicing compatible with both Scala 2 and Scala 3?


Context

One of the differences between Scala 2 and Scala 3 is the syntax for varargs splices.

So given

def combine(strings: String*): Unit = {
  println(strings.mkString("; "))
}

val list = List("a", "b")

In Scala 2 one can call the function with:

combine((list ++ list): _*)

In Scala 3 the syntax is:

combine((list ++ list)*)

Question

If I want to write code which compiles and works in both Scala 2 and Scala 3, what are the syntax options, if I want to continue to use varargs?

I know I can define the argument type to be Seq[String] instead, but that's giving up the varargs convenience.

Assume I can change both the method definition and call sites.


Solution

  • You can use -Xsource:3 (possibly with -Xsource-feature, or with -Xsource:3-cross instead) in scalacOptions for Scala 2.

    Then:

    combine((list ++ list)*)
    

    would compile in both Scala 2 and Scala 3.