Instead of
开发者_StackOverflow社区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?
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.
You could define it as
type Param = (String, String)
type Configuration = Seq[Param]
def foo(configuration : Configuration)
the user has to construct a Seq instance
foo(List("1"->"2"))
which is not optimal.
精彩评论