繁体   English   中英

如何在Scala中匹配嵌套的选项值

[英]How to match nested option values in scala

 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行,我希望能够对其进行模式匹配。 有人知道吗?

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

case Row(job_id, title) =>

并检查里面。

(当你得到一个Row从星火,它不包含任何Option[String]小号无论如何,只是空或非空String S(/ Int的/ etc。)。

您也可以使用自定义提取器对象 ,例如

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

然后

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

将您的x title绑定为None ,并且不匹配

new Row("hello", notAString) 

暂无
暂无

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

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