Scala:如何将可变参数指定为类型? [英] Scala: how to specify varargs as type?
问题描述
代替
def foo(configuration: (String, String)*)
我希望能够写:
type Configuration = (String, String)*
def foo(configuration: Configuration)
主要用例是在子类中覆盖时提供简单的方法签名
The main use case is to provide an easy method signature when overriding in subclasses
更新:我可以靠近
type Param = (String, String)
def foo(configuration: Param*)
但是有没有更好的方法?
But is there a way of doing it better?
推荐答案
不,*
只允许用于 ParamType,即匿名函数或方法的参数类型.
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 重复参数语法:ParamType ::= Type ‘’ 最后一个值参数部分的参数可以以"为后缀,例如(..., x:T *).这种重复参数的类型方法内部是序列输入 scala.Seq[T].方法与重复参数 T * 取一个可变数量的 T 类型参数.
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.
编译器错误@Eastsun 的例子在第一行,而不是第二行.这不应该被允许:
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
我提出了一个错误.
这与按名称参数的限制类似.在这种情况下,编译器会阻止创建类型别名:
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.
这篇关于Scala:如何将可变参数指定为类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!