2

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?

1

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

More idiomatic: vs.mapConserve { case null => "" case x => x }
Actually it's not recommended to use null in Scala directly.
The data in question already uses null. It's not forbidden to use the null keyword; you just want to limit it to a boundary like this one, when ingesting data. And to keep null out of API. They want Option to be a value class to avoid needless creating Option objects as you do here; in that case, your expr would be more appetizing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.