簡體   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