Feynman27 Feynman27 - 1 year ago 97
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download