【问题标题】:can anyone explain what @ _* mean in this code snippet? [duplicate]谁能解释这段代码片段中 @ _* 的含义? [复制]
【发布时间】:2018-06-04 10:52:28
【问题描述】:
def swapElementsOfArray(array: Array[Int]) = 
    array match {
        case Array(x, y, z @ _*) => Array(y, x) ++ z
        case _ => array
}

我不明白这里如何使用 @ _*。谁能帮忙解释一下?提前谢谢你。

【问题讨论】:

    标签: scala


    【解决方案1】:

    运算符_* 引用一系列元素,在您的情况下,它是数组的“尾部”。

    运算符@ 允许您将匹配的模式绑定到变量,在您的情况下为“z”

    因此,使用z @ _*,您将分配给 Z 未使用的数组的其余部分,但您需要稍后参考它。

    val a= Array(2, 1, 3, 5, 3, 2)
    def swapElementsOfArray(array: Array[Int]) =
      array match {
        case Array(x, y, z @ _*) => Array(y, x) ++ z
        case _ => array
      }
    
    swapElementsOfArray(a).toString
    

    res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 5, 3, 2

    z 将是“3,5,3,2”,您不需要使用它,但您需要参考。

    【讨论】:

      【解决方案2】:

      在这个具体示例中,_* 表示“数组的其余部分”。

      z @ 部分是用于将变量名绑定到模式的标准模式匹配语法

      请注意,_* 运算符是适用于任何 vararg 参数的通用运算符,有时也称为“splat 运算符”。

      您可以在规范中阅读:https://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html#repeated-parameters

      这是相关的句子:

      此规则的唯一例外是如果最后一个参数通过_* 类型注释标记为序列参数。如果将上面的m 应用于参数(e1,…,en,e′: _*),则该应用程序中m 的类型将被视为(p1:T1,…,pn:Tn,ps:scala.Seq[S])

      这适用于匹配和传递可变参数。例如,splat 运算符可用于传递需要可变参数的序列。

      例子:

      val s = Seq(1, 2, 3)
      val a1 = Array(s) // does not compile
      val a2 = Array(s: _*) // compiles, s is passed as vararg
      
      a2 match {
        case Array(s @ _*) => s // s now contains all the elements of a2
      }
      
      a2 match {
        case Array(head, tail @ _*) => head // tail contains all the elements except the first
        case _ => ??? // empty list!
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-22
        • 2011-02-11
        • 1970-01-01
        • 2021-04-24
        相关资源
        最近更新 更多