Scala: how to specify varargs as type?

Instead

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

I would like to write:

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

The primary use case is to provide a simple method signature when overriding in subclasses

UPDATE: I can get closer to

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

But is there a way to make this better?

+6
types scala
source share
3 answers

No, * is only allowed for the ParamType parameter, which is the parameter type for an anonymous function or method.

4.6.2 Duplicate parameters Syntax: ParamType :: = Type 'The last value of the parameter of the parameter section may be the suffix "", for example. (..., x: T *). The type of such a repeating parameter inside the method is a sequence of type scala.Seq [T]. Methods with repeating T * parameters accept a variable number of arguments of type T.

The compiler error @Eastsun example is on the first line, not the second. This should not be allowed:

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

I raised a mistake .

This is a similar limitation for By-Name parameters. In this case, the compiler prevents the creation of an alias of the type:

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

Your last attempt is the standard way of expressing this.

+9
source share

I think you could use

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

But this leads to a compiler failure (2.8.0.r21161-b20100314020123). It seems to be a scala compiler error.

+2
source share

You can define it as

 type Param = (String, String) type Configuration = Seq[Param] def foo(configuration : Configuration) 

user must build an instance of Seq

 foo(List("1"->"2")) 

which is not optimal.

+1
source share

All Articles