【问题标题】:Scala: how to specify varargs as type?Scala:如何将可变参数指定为类型?
【发布时间】:2011-01-27 14:59:09
【问题描述】:

而不是

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

我希望能够写作:

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

主要用例是在子类中覆盖时提供简单的方法签名

更新: 我可以靠近

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

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

【问题讨论】:

    标签: scala types


    【解决方案1】:

    不,* 只允许用于 ParamType,即匿名函数或方法的参数类型。

    4.6.2 重复参数语法:ParamType ::= Type ‘’ 最后一个值 参数部分的参数可以 后缀为“”,例如(..., x:T *)。 这种重复参数的类型 然后在方法内部是序列 键入 scala.Seq[T]。方法与 重复参数 T * 取一个 可变数量的 T 类型参数。

    编译器错误@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】:

      我认为你可以使用

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

      但这会使编译器崩溃(2.8.0.r21161-b20100314020123)。这似乎是 scala 编译器的一个错误。

      【讨论】:

        【解决方案3】:

        你可以定义为

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

        用户必须构造一个 Seq 实例

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

        这不是最优的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-11
          • 2017-07-28
          • 2011-11-05
          • 2015-02-13
          • 2012-05-13
          • 2019-11-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多