简体   繁体   English

Scala:如何将varargs指定为类型?

[英]Scala: how to specify varargs as type?

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? 但有没有办法做得更好?

No, the * is only allowed on a ParamType, that is the type of a parameter to a anonymous function or a method. 不, *仅允许在ParamType上,即匿名函数或方法的参数类型。

4.6.2 Repeated Parameters Syntax: ParamType ::= Type ' ' The last value parameter of a parameter section may be suffixed by “ ”, eg (..., x:T *). 4.6.2重复参数语法:ParamType :: = Type' '参数部分的最后一个值参数可以后缀“ ”,例如(...,x:T *)。 The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T ]. 然后,方法中的这种重复参数的类型是序列类型scala.Seq [T]。 Methods with repeated parameters T * take a variable number of arguments of type T. 重复参数T *的方法采用类型为T的可变数量的参数。

The compiler bug @Eastsun's example is in the first line, not the second. 编译错误@Eastsun的例子是在第一行,而不是第二行。 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. 这与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). 但它使编译器崩溃(2.8.0.r21161-b20100314020123)。 It seems a bug of the scala compiler. 这似乎是scala编译器的一个bug。

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 用户必须构造一个Seq实例

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

which is not optimal. 这不是最佳的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM