I want to define a function:
def convert(x: Option[String]): Option[String] = ...
When x
is Some(str)
and the str
is empty after trimming, it will be converted to a None, otherwise, it will be a Some
with trimmed string.
So, the test case will be:
convert(Some("")) == None
convert(Some(" ")) == None
convert(None) == None
convert(Some(" abc ")) == Some("abc")
I can write it as:
def convert(x: Option[String]): Option[String] = x match {
case Some(str) if str.trim()!="" => Some(str.trim())
case _ => None
}
But I hope to find a simpler implementation(one-line).
What about this:
def convert(x: Option[String]) =
x.map(_.trim()).filterNot(_.isEmpty())
UPDATE: Alternative syntaxes suggested by @JamesMoore and @PeterSchmitz:
x map {_.trim} filterNot {_.isEmpty}
x map (_.trim) filterNot (_.isEmpty)
And as usual there is also the for comprehension alternative syntax (which is a syntax sugar for filter and map)
def convert(o: Option[String]): Option[String] =
for (x <- o if !x.isEmpty) yield x
def convert(x: Option[String]) = x.filter(s => s.trim.nonEmpty)
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