[英]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!")
}
For the code above when I try to match with an option type it actually matches with _
and gives me a warning shown below: 对于上面的代码,当我尝试与选项类型匹配时,它实际上与
_
匹配,并给我以下警告:
warning: non-variable type argument String in type pattern Option[String] is unchecked since it is eliminated by erasure
Basically the Row struct represents a sql row with nullable values and I want to be able to pattern match to it. 基本上,Row结构代表具有可为空值的sql行,我希望能够对其进行模式匹配。 Does anyone know how?
有人知道吗?
Just don't use type patterns ( : String
and : Option[String]
), because null
doesn't match them. 只是不要使用类型模式(
: String
和: Option[String]
),因为null
与它们不匹配。 Write 写
case Row(job_id, title) =>
and check inside. 并检查里面。
(When you get a Row
from Spark, it won't contain any Option[String]
s anyway, just null or non-null String
s(/ Int
s/etc.). (当你得到一个
Row
从星火,它不包含任何Option[String]
小号无论如何,只是空或非空String
S(/ Int
的/ etc。)。
You could also use custom extractor objects , eg 您也可以使用自定义提取器对象 ,例如
object OptString {
def unapply(x: String) = Some(Option(x))
}
// repeat for other types
then 然后
case Row(job_id, OptString(title)) =>
will bind title
to None
for your x
and wouldn't match for 将您的
x
title
绑定为None
,并且不匹配
new Row("hello", notAString)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.