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

Scala String*类型(在函数args中)

  •  -1
  • hummingBird  · 技术社区  · 8 年前

    我有以下方法:

    def m(a: String*) = { // ... }
    

    我想知道星号(*)在这个语法中有什么用途?我显然是斯卡拉的新手。我在谷歌上搜索了,但可能搜索错了。如有任何帮助,我们将不胜感激。

    干杯!

    3 回复  |  直到 8 年前
        1
  •  5
  •   jub0bs    8 年前

    它被称为“var args”(变量参数)。

    def concat(strs: String*): String = strs.foldLeft("")(_ ++ _)
    

    斯卡拉回复

    scala> def concat(strs: String*): String = strs.foldLeft("")(_ ++ _)
    concat: (strs: String*)String
    
    scala> concat()
    res6: String = ""
    
    scala> concat("foo")
    res7: String = foo
    
    scala> concat("foo", " ", "bar")
    res8: String = foo bar
    
        2
  •  4
  •   Jörg W Mittag    8 年前

    这叫做 repeated parameter (see Section 4.6.3 of the Scala Language Specification) .

    重复的参数允许方法获取相同类型的参数的数目未指定 T ,可在绑定到类型为的参数的方法体内部访问 Seq[T] .

    在你的情况下,在方法内部 m ,参数 a 将绑定到 Seq[String] .

        3
  •  1
  •   stefanobaghino    8 年前

    这是定义接受可变参数数的方法的语法。

    你的 m 方法可以接受0、1或更多参数,这些都是有效的调用:

    m()
    m("hello")
    m("hello", "world")
    

    如果使用适当的类型提示,也可以将集合传递给该方法:

    val words = Seq("hello", "world")
    m(words: _*)
    

    你可以玩这个代码 here on Scastie (在我实施 米 作为输入字符串的连接)。

    推荐文章