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).
str.trim
twice which is clearly something to avoid. – Feminacy