4

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Robin
  • 167
  • 1
  • 2
  • 8

4 Answers4

5

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)
Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52
4

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"
} 
Samar
  • 2,091
  • 1
  • 15
  • 18
2

I guess idiomatic way looks like this:

val myString : Option[String] = ...
myString
  .filterNot(StringUtils.isEmpty)
  .foreach(builder.queryParam("localStr", _))
Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
1

Option[String] can store 2 types of value either Some(String) or None so when u dont need to check for null u just check for None with the help of scala match case as follows

val myString : Option[String] = Some("ss")

 myString match {
   case Some(str)=>str.filter(localStr=> StringUtils.isEmpty(localStr))
    .foreach(localStr=> builder.queryParam("localStr", localStr))
   case None => //do whatever you want while condition failure
 }
Sandeep Purohit
  • 3,652
  • 18
  • 22