Michael
Michael

Reputation: 42050

Simple string manipulation in Scala

Suppose I need a function stripBang(s: String): Option[String]:

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

Answers (3)

sjrd
sjrd

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

Andreas Neumann
Andreas Neumann

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

4lex1v
4lex1v

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

Related Questions