我有以下Scala代码
代码:
object ReplaceNulls {
def main(args:Array[String]) = {
val myList = List("surender", "", null)
val myUpdatedList = myList.map {
case a: String => a
case null => "OTHERS"
case "" => "OTHERS"
}
println(myUpdatedList)
}
以上代码给出了以下输出
List(surender, , OTHERS)
但预期产量低于
List(surender,OTHERS,OTHERS)
我的代码出了什么问题?
答案 0 :(得分:2)
因为“”也是字符串类型,并且与第一种情况匹配,即object ReplaceNulls {
def main(args:Array[String])={
val myList = List("surender","",null)
val myUpdatedList = myList.map { x => x match{
case "" =>"OTHERS"
case a:String => a
case null => "OTHERS"
}
}
println(myUpdatedList)
}
}
。您可以尝试更改案例陈述的顺序
{{1}}