Reputation: 198238
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).
Upvotes: 9
Views: 3531
Reputation: 166
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
Upvotes: 1
Reputation: 340733
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)
Upvotes: 17