Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
In Scala, varargs (variable-length argument lists) allow you to pass a variable number of arguments to a function or method. They are similar to Java's varargs. In Scala, you denote a varargs parameter using the _*
type annotation.
If you want a method to accept a variable number of arguments, you define it like this:
def functionName(arg1: Type1, arg2: Type2, varArgName: ArgType*): ReturnType = { // method body }
Here's a simple example where we define a method printAll
that can accept a variable number of String
arguments:
def printAll(strings: String*): Unit = { strings.foreach(println) } printAll("apple", "banana", "cherry") // This will print: // apple // banana // cherry
If you have a sequence like a List or Array and you want to pass its elements as varargs to a method, you can use the :_*
type ascription:
val fruits = List("apple", "banana", "cherry") printAll(fruits: _*) // This will also print: // apple // banana // cherry
You can mix varargs with other parameters, but the varargs must be the last parameter in the list:
def printWithPrefix(prefix: String, values: String*): Unit = { values.foreach(v => println(s"$prefix: $v")) } printWithPrefix("Fruit", "apple", "banana", "cherry") // This will print: // Fruit: apple // Fruit: banana // Fruit: cherry
Varargs in Scala provide flexibility in function and method definitions, allowing for a dynamic number of arguments. This feature is especially useful when you're not sure ahead of time how many arguments might need to be passed to a method, or when designing utility and API functions meant to be called with varying argument counts.
How to use varargs in Scala:
def printValues(values: String*): Unit = { values.foreach(println) } printValues("One", "Two", "Three")
Passing variable number of arguments in Scala:
def sum(values: Int*): Int = { values.sum } val result = sum(1, 2, 3, 4, 5)
Scala varargs vs Seq vs Array:
Seq
in the function body. You can convert varargs to other collections like Array
if needed.def processSeq(seq: Seq[String]): Unit = { seq.foreach(println) } val varargs: Seq[String] = "One" :: "Two" :: "Three" :: Nil processSeq(varargs)
Pattern matching with varargs in Scala:
def processArgs(args: Any*): String = args match { case Seq(x, y) => s"Two arguments: $x, $y" case Seq(x, y, _*) => s"At least two arguments: $x, $y, and more" case _ => "No or unknown number of arguments" }
Handling null or empty varargs in Scala:
Option
type and check for presence.def processValues(values: String*): Unit = { val nonEmptyValues = values.filterNot(_.isEmpty) nonEmptyValues.foreach(println) }
Advanced use cases for varargs in Scala:
def combineStrings(separator: String, values: String*): String = { values.mkString(separator) } val result = combineStrings(", ", "One", "Two", "Three")