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

fdx2calv  于 2021-06-29  发布在  Hive
关注(0)|答案(1)|浏览(344)

我正在用scala编写一个hiveudf(因为我想学习scala)。为此,我必须重写三个函数: evaluate , initialize 以及 getDisplayString .
在初始化函数中,我必须:
接收一组 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方法来改进上面的代码?

xwbd5t1u

xwbd5t1u1#

模式通常包含其他模式。类型 x 这是绳子。

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

“任意多个参数”的惯用用法是“序列模式”,它匹配任意参数:

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

这个答案不应该被解释为提倡匹配您的方式回到类型安全。

相关问题