Freewind
Freewind

Reputation: 198238

How to convert a Some(" ") to None in one-line?

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

Answers (3)

Eric D
Eric D

Reputation: 41

def convert(x: Option[String]) = x.filter(s => s.trim.nonEmpty)

Upvotes: 1

Antoine Comte
Antoine Comte

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

Tomasz Nurkiewicz
Tomasz Nurkiewicz

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

Related Questions