Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Syntactic Sugar for converting to `Option`

Tags:

scala

When working in Scala, I often want to parse a field of type [A] and convert it to a Option[A], with a single case (for example, "NA" or "") being converted to None, and the other cases being wrapped in some.

Right now, I'm using the following matching syntax.

match {
  case "" => None
  case s: String => Some(s)
}
// converts an empty String to None, and otherwise wraps it in a Some.

Is there any more concise / idiomatic way to write this?

like image 405
Vincent Tjeng Avatar asked Jan 27 '15 20:01

Vincent Tjeng


1 Answers

There are a more concise ways. One of:

Option(x).filter(_ != "")
Option(x).filterNot(_ == "")

will do the trick, though it's a bit less efficient since it creates an Option and then may throw it away.

If you do this a lot, you probably want to create an extension method (or just a method, if you don't mind having the method name first):

implicit class ToOptionWithDefault[A](private val underlying: A) extends AnyVal {
  def optNot(not: A) = if (underlying == not) None else Some(underlying)
}

Now you can

scala> 47.toString optNot ""
res1: Option[String] = Some(47)

(And, of course, you can always create a method whose body is your match solution, or an equivalent one with if, so you can reuse it for that particular case.)

like image 55
Rex Kerr Avatar answered Oct 19 '22 04:10

Rex Kerr