Scala Check optional string is null or empty

Robin picture Robin · Sep 2, 2016 · Viewed 8.6k times · Source

I am a newbie to Scala and I want to learn how can I add null and empty check on an optional string?

val myString : Option[String]

if (null != myString) {
  myString
    .filter(localStr=> StringUtils.isEmpty(localStr))
    .foreach(localStr=> builder.queryParam("localStr", localStr))
}

Above code works but I want to learn some elegant way of writing same check. Any help is highly appreciated,

thanks

Answer

Andreas Neumann picture Andreas Neumann · Sep 2, 2016

There is a quite convenient way using the Option constructor.

scala> Option("Hello Worlds !")
res: Option[String] = Some(Hello Worlds !)


scala> Option(null)
res: Option[Null] = None

So if you would have list of Strings with possible null values you can use a combination of Option and flatten:

scala> List("Speak", "friend", null, "and", null ,"enter").map(s => Option(s)) .flatten
res: List[String] = List(Speak, friend, and, enter)