Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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).

like image 263
Freewind Avatar asked Mar 05 '12 15:03

Freewind


3 Answers

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)
like image 157
Tomasz Nurkiewicz Avatar answered Sep 25 '22 04:09

Tomasz Nurkiewicz


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
like image 43
Antoine Comte Avatar answered Sep 25 '22 04:09

Antoine Comte


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

like image 41
Eric D Avatar answered Sep 26 '22 04:09

Eric D