代码之家  ›  专栏  ›  技术社区  ›  IttayD

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

  •  6
  • IttayD  · 技术社区  · 16 年前

    而不是

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

    我想能够写:

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

    主要的用例是在子类中重写时提供一个简单的方法签名。

    更新: 我可以靠近

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

    但是有没有更好的方法呢?

    3 回复  |  直到 16 年前
        1
  •  9
  •   retronym    16 年前

    不, * 只允许在paramtype上使用,paramtype是匿名函数或方法的参数类型。

    4.6.2重复参数语法:paramtype::=type–152 最后一个值 参数部分的参数可以 以“156”作为后缀 ,例如(…,x:t*)。 这种重复参数的类型 方法里面是序列 键入scala.seq[t]。方法与 重复参数t*取a t类型的参数的变量数。

    编译器bug@eastsun的例子在第一行,而不是第二行。这是不允许的:

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

    我养了一只 bug .

    这与按名称参数的限制类似。在这种情况下,编译器会阻止创建类型别名:

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

    你最后的尝试是表达这一点的标准方法。

        2
  •  2
  •   Eastsun    16 年前

    我想你可以用

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

    但它会导致编译器崩溃(2.8.0.r21161-b20100314020123)。这似乎是scala编译器的一个缺陷。

        3
  •  1
  •   Thomas Jung    16 年前

    你可以定义为

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

    用户必须构造一个seq实例

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

    这不是最优的。