Google News
logo
Scala - Interview Questions
What are the differences between 'varargs' in Java and 'varargs' in Scala?
In both Java and Scala, varargs (variable arguments) allow a method to accept a variable number of arguments of the same type. However, there are some differences in how varargs are defined and used in Java and Scala:

1. Syntax :
   * Java : In Java, varargs are denoted by an ellipsis (`...`) following the type of the last parameter in the method signature.
   * Scala: In Scala, varargs are denoted by a trailing `*` symbol following the type of the parameter in the method signature.

2. Type of Arguments :
   * Java: Varargs in Java are internally treated as an array of the specified type. Inside the method, you can access the varargs as an array.
   * Scala: Varargs in Scala are internally treated as a sequence of the specified type. Inside the method, you can access the varargs as a `Seq` or convert them to other collection types if needed.

3. Passing Arguments :
   * Java: When calling a method with varargs in Java, you can pass individual arguments, an array of arguments, or nothing at all. The Java compiler handles the conversion accordingly.
   * Scala: When calling a method with varargs in Scala, you can pass individual arguments directly, as well as pass an array or a sequence of arguments using the `:_*` syntax.

Here's an example that demonstrates the usage of varargs in Java and Scala :
Java :
// Java
public void printNames(String... names) {
    for (String name : names) {
        System.out.println(name);
    }
}

printNames("John", "Jane", "Mike");​

Scala :
// Scala
def printNames(names: String*): Unit = {
  for (name <- names) {
    println(name)
  }
}

printNames("John", "Jane", "Mike")​

In both cases, the `printNames` method accepts a variable number of `String` arguments. The method body iterates over the arguments and prints each name.
Advertisement