Reputation: 3267
I'm attempting to replace the null elements of a Scala list with an empty value using map
. 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?
Upvotes: 2
Views: 3672
Reputation: 1578
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.
Upvotes: 9