Rap*_*oth 6 scala apache-spark
我想知道为什么我不能在包含空值(字符串)的Spark(2.1)行上进行模式匹配:
val r = Row(null:String)
r match {case Row(s:String) => println("row is null")}
Run Code Online (Sandbox Code Playgroud)
scala.MatchError:[null](类org.apache.spark.sql.catalyst.expressions.GenericRow)
Row 在这里并没有真正发挥重要作用,我们可以简化:
val r = null: String
r match {case s:String => println("s is null")}
Run Code Online (Sandbox Code Playgroud)
您可以检查模式匹配是否仍然失败.这是因为类型图案像s: String被具体地定义为不匹配null:
类型模式T具有以下形式之一:
- 对C,pC或T#C类的引用.此类型模式匹配给定类的任何非null实例 ...
isInstanceOf表现得像这样:null.isInstanceOf[String]是false.
所以,如果你想匹配null,你可以
1)完全null用作模式:
r match {
case s: String => println("r is not null")
case null => println("r is null")
}
Run Code Online (Sandbox Code Playgroud)
2)使用"catch-all"模式_或变量:
r match {
case s: String => println("r is not null")
case s => println("matches only if r is null or not a String")
}
Run Code Online (Sandbox Code Playgroud)
或者,如果我们放Row回去,你会写
r match {
case Row(s: String) => println("r contains non-null")
case Row(null) => println("r contains null")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1041 次 |
| 最近记录: |