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

时间:2016-06-05 19:13:25

标签: scala hive udf

我正在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方法来改进上面的代码?

1 个答案:

答案 0 :(得分:0)

包含其他模式的模式的典型特征。这里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

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