Reputation: 42050
Suppose I need a function stripBang(s: String): Option[String]
:
s
is either null or empty return None
s(0) == '!'
return None
Some(s.tail)
I am writing the function as follows:
def stripBang(s: String) = Option(s).flatMap(PartialFunction.condOpt(_) {
case s if s.nonEmpty && s(0) == '!' => s.tail
})
It seems to work but looks clumsy. How would you suggest improve it?
Upvotes: 0
Views: 464
Reputation: 22085
So many complicated answers! I would suggest this simple function, which clearly exposes the intent:
def stripBang(s: String): Option[String] =
if (s != null && s.nonEmpty && s(0) != '!') Some(s.tail)
else None
Upvotes: 4
Reputation: 10884
I'd go with an implicit class:
Implementation
implicit class StripBang(s: String) {
def stripBang = s match {
case null => None
case "" => None
case s : String if s startsWith "!" => None
case s : String => Some( s )
}
}
Usage
scala> "test".stripBang
res3: java.io.Serializable = Some(test)
scala> "!test".stripBang
res4: java.io.Serializable = None
scala> "".stripBang
res5: Option[String] = None
scala> val s : String = null
s: String = null
scala> s.stripBang
res6: java.io.Serializable = None
Upvotes: 2
Reputation: 21547
Why not startsWith
?
def stripBang(s: String) = Option(s).flatMap(str => if (str.startsWith("!") || str.isEmpty()) None else Some(str.tail))
Upvotes: 3