Surender Raja Surender Raja - 3 months ago 10
Scala Question

Why is it the empty element of a List are not replaced with default value in Scala?

I have the below Scala Code

Code:

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)
}


This above Code gives me the below Output

List(surender, , OTHERS)


But the expected output is below

List(surender,OTHERS,OTHERS)


What went wrong in my code ?

Answer

Because "" is also of type string and will match the first case i.e case a:String. You can try changing the order of case statements

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)

 }

}