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
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)
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With