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?
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].
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With