【问题标题】:How does scala match on Arrays?scala 如何在数组上匹配?
【发布时间】:2011-10-31 18:34:49
【问题描述】:

查看 Scala 代码,方便的数组创建语法是通过在object Array 中添加一个apply 方法来实现的。起初,我认为这是通过案例类以某种方式实现的,因为您可以运行以下内容,但情况似乎并非如此:

Array(1,2,3) match { case Array(a, b, c) => a + b + c }

我知道我还需要查看WrappedArray 和所有超类,但我无法弄清楚 scala 如何在数组上实现这种匹配(我需要更加熟悉 scala 集合类层次结构)。它当然不适用于普通课程。

scala>  class A(val x: Int)
scala>  new A(4) match { case A(x) => x }
<console>:9: error: not found: value A
              new A(4) match { case A(x) => x }
                                    ^
<console>:9: error: not found: value x
              new A(4) match { case A(x) => x }

他们如何让它与 Array 一起使用?

【问题讨论】:

    标签: scala


    【解决方案1】:

    只要您有一个带有unapplyunapplySeq(在可变参数的情况下)方法返回OptionBoolean 的对象,您就可以在任何类上使用此语法进行模式匹配。这些被称为提取器。来自对象Array 的有问题的行是

      def unapplySeq[T](x: Array[T]): Option[IndexedSeq[T]] =
        if (x == null) None else Some(x.toIndexedSeq) 
    

    在您的示例中,您可以使用它来匹配

    class A(val x: Int)
    
    object A {
      def unapply(a: A) = Some(a.x)
    }
    

    现在

    scala> new A(4) match { case A(x) => x }
    res1: Int = 4
    

    Scala 中的编程chapter on extractors 可能很有用。

    对于案例类,unapply 方法只是免费提供的方法之一,还有toStringequals 等。

    请注意,提取器不必与所讨论的类同名,也不必在object 对象中定义。例如,在您的情况下,您可以同样写

    val xyz = new { def unapply(a: A) = Some(a.x) } //extending java.lang.Object
    
    new A(4) match { case xyz(x) => x }             //Int = 4
    

    【讨论】:

    • 只是为了精确:不可能添加到 JVM 数组类,但 unapply/unapplySeq 通常定义在对象中,而不是类中。 Scala 可能并且确实添加了一个 Array 对象。
    猜你喜欢
    • 2021-04-08
    • 2011-10-02
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多