繁体   English   中英

Scala:如何简化嵌套模式匹配语句

[英]Scala: How to simplify nested pattern matching statements

我正在Scala中编写一个Hive UDF(因为我想学习scala)。 为此,我必须覆盖三个函数: evaluateinitializegetDisplayString

在初始化函数中,我必须:

  • 接收ObjectInspector数组并返回ObjectInspector
  • 检查数组是否为空
  • 检查阵列是否具有正确的大小
  • 检查数组是否包含正确类型的对象

为此,我使用模式匹配并提出以下功能:

  override def initialize(genericInspectors: Array[ObjectInspector]): ObjectInspector = genericInspectors match {
    case null => throw new UDFArgumentException(functionNameString + ": ObjectInspector is null!")
    case _ if genericInspectors.length != 1 => throw new UDFArgumentException(functionNameString + ": requires exactly one argument.")
    case _ => {
      listInspector = genericInspectors(0) match {
        case concreteInspector: ListObjectInspector => concreteInspector
        case _ => throw new UDFArgumentException(functionNameString + ": requires an input array.")
     }
      PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(listInspector.getListElementObjectInspector.asInstanceOf[PrimitiveObjectInspector].getPrimitiveCategory)
    }
  }

尽管如此,我的印象是函数可以变得更清晰,并且通常更漂亮,因为我不喜欢有太多缩进级别的代码。

是否有一种惯用的Scala方法来改进上面的代码?

模式通常包含其他模式。 这里的x的类型是String。

scala> val xs: Array[Any] = Array("x")
xs: Array[Any] = Array(x)

scala> xs match {
     | case null => ???
     | case Array(x: String) => x
     | case _ => ???
     | }
res0: String = x

“任意数量的args”的习语是“序列模式”,它匹配任意args:

scala> val xs: Array[Any] = Array("x")
xs: Array[Any] = Array(x)

scala> xs match { case Array(x: String) => x case Array(_*) => ??? }
res2: String = x

scala> val xs: Array[Any] = Array(42)
xs: Array[Any] = Array(42)

scala> xs match { case Array(x: String) => x case Array(_*) => ??? }
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230)
  ... 32 elided

scala> Array("x","y") match { case Array(x: String) => x case Array(_*) => ??? }
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230)
  ... 32 elided

这个答案不应被解释为主张回归类型安全。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM