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