Feynman27 Feynman27 - 1 month ago 7x
Scala Question

Replace null values in a list with another value in Scala

I'm attempting to replace the null elements of a Scala list with an empty value using

. I currently have:

val arr = Seq("A:B|C", "C:B|C", null)
val arr2 = arr.map(_.replaceAll(null, "") )

This gives me a NullPointerExpection. What is the best way to do this?


You're trying to replace a null character in a string instead of replacing a null string in Seq. So here is a correct way:

val arr2 = arr.map(str => Option(str).getOrElse(""))

The Option here will produce Some(<your string>) if the value is not null and None otherwise. getOrElse will return your string if it's not null or empty string otherwise.