Java – Scala check optional string is null or empty

I'm new to scala. I want to learn how to add null and null checks to optional strings?

val myString : Option[String]

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

The above code works, but I want to learn some elegant ways to write the same check Thank you very much for any help,

thank you

Solution

There is a very convenient way to use the option constructor

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


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

Therefore, if you have a list of strings that may be null, you can use a combination of option and flatten:

scala> List("Speak","friend",null,"and","enter").map(s => Option(s)) .flatten
res: List[String] = List(Speak,friend,and,enter)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>