Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: how to specify varargs as type?

Tags:

types

scala

Instead of

def foo(configuration: (String, String)*)

I'd like to be able to write:

type Configuration =  (String, String)*
def foo(configuration: Configuration)

The main use case is to provide an easy method signature when overriding in subclasses

UPDATE: I can come close by

type Param = (String, String)
def foo(configuration: Param*)

But is there a way of doing it better?

like image 343
IttayD Avatar asked Mar 15 '10 10:03

IttayD


People also ask

How do you pass variables in Scala?

Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array[String].

What is Varargs parameter?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.


2 Answers

No, the * is only allowed on a ParamType, that is the type of a parameter to a anonymous function or a method.

4.6.2 Repeated Parameters Syntax: ParamType ::= Type ‘’ 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 ]. Methods with repeated parameters T * take a variable number of arguments of type T.

The compiler bug @Eastsun's example is in the first line, not the second. This should not be allowed:

scala> type VarArgs =  (Any*)
defined type alias VarArgs

I've raised a bug.

This is similar restriction to By-Name Parameters. In this case, the compiler prevents the creation of the type alias:

scala> type LazyString = (=> String) <console>:1: error: no by-name parameter type allowed here
       type LazyString = (=> String)

Your final attempt is the standard way to express this.

like image 104
retronym Avatar answered Oct 20 '22 06:10

retronym


I think you could use

type Configuration =  ((String, String)*)
def foo(configuration: Configuration)

But it makes the compiler crash(2.8.0.r21161-b20100314020123). It seems a bug of the scala compiler.

like image 28
Eastsun Avatar answered Oct 20 '22 08:10

Eastsun