【问题标题】:How to match nested option values in scala如何匹配scala中的嵌套选项值
【发布时间】:2019-08-06 00:37:03
【问题描述】:
 let x = new Row(job_id="hello", title=null)

 x match {
     case Row(
           job_id: String,
           title: Option[String]) => println("successful match")
     case _ => println("failed!")

}

对于上面的代码,当我尝试与选项类型匹配时,它实际上与_ 匹配,并给出如下所示的警告:

warning: non-variable type argument String in type pattern Option[String] is unchecked since it is eliminated by erasure

基本上,Row 结构表示具有可为空值的 sql 行,我希望能够对其进行模式匹配。有谁知道怎么做?

【问题讨论】:

  • 行在哪里定义?另外,我认为你想要 None,而不是 null。
  • 如果您使用Row,这是不可能的,因为Row 使用原始值,其中包括用于缺少值的nulls。
  • Row 来自 spark 所以它实际上是一个空值。

标签: sql scala apache-spark pattern-matching


【解决方案1】:

不要使用类型模式(: String: Option[String]),因为null 不匹配它们。写

case Row(job_id, title) =>

然后检查里面。

(当您从 Spark 获得 Row 时,它不会包含任何 Option[String]s,只是 null 或非 null Strings(/Ints/etc.)。

您也可以使用自定义extractor objects,例如

object OptString {
  def unapply(x: String) = Some(Option(x))
}
// repeat for other types

然后

case Row(job_id, OptString(title)) =>

将为您的 x 绑定 titleNone 并且不匹配

new Row("hello", notAString) 

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 2017-12-16
    • 2020-03-06
    • 1970-01-01
    • 2013-09-13
    • 2019-06-15
    • 2021-04-04
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多