Feynman27
Feynman27

Reputation: 3267

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

Answers (1)

Zyoma
Zyoma

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

Related Questions