Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Check optional string is null or empty

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

like image 462
Robin Avatar asked Dec 14 '22 04:12

Robin


2 Answers

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)
like image 114
Andreas Neumann Avatar answered Dec 21 '22 11:12

Andreas Neumann


Pattern matching will help in simplifying your code:

myString match {
case Some(s) if(!s.isEmpty) => s.foreach(localStr=> builder.queryParam("localStr", localStr))
case _ => "No String"
} 
like image 41
Samar Avatar answered Dec 21 '22 10:12

Samar