Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala variadic functions and Seq

As far as I know, traits like List or Seq are implemented in the Scala standard library instead of being part of the language itself.

There is one thing that I do not understand, though: one has a syntax for variadic functions that looks like

def foo(args: String*) = ...

Internally one has access to args and it will be a Seq.

It is not clear to me whether:

  • Seq is considered a special data structure enough to appear as part of the language, or
  • the * notation here is a particular case of a more general syntax that manages to avoid any references to concrete data structures interfaces.

Does anyone know which one is the correct intepretation?

like image 770
Andrea Avatar asked Aug 13 '12 09:08

Andrea


People also ask

How do you use Variadic arguments?

It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter. This enables access to variadic function arguments. *argN* is the last fixed argument in the variadic function.

How do you pass parameters to a Scala function?

Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.

What does _* mean in Scala?

: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs.

Is printf variadic function?

The C printf() function is implemented as a variadic function. This noncompliant code example swaps its null-terminated byte string and integer parameters with respect to how they are specified in the format string.


2 Answers

It is indeed somewhat a 'blur' between language and library. The Scala Language Specification v2.9 states in §4.6.2 Repeated Parameters:

The last value parameter of a parameter section may be suffixed by “*”, e.g. (..., x:T*). The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T].

So when you use repeated arguments, it is assumed that scala.Seq is available at runtime (which should be the case, as it is part of the standard library).

like image 96
0__ Avatar answered Oct 19 '22 20:10

0__


I think it is the first one. There are a couple of types that the language demands to exist although they aren't really part of the language. With Seq you found one.

like image 33
Jens Schauder Avatar answered Oct 19 '22 20:10

Jens Schauder