Scala Syntactic sugar for conversion to `Option`

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

I am now 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 a more concise / idiomatic way to write this?

+6
source share
3 answers

There are more concise ways. One of:

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

will do the trick, although it is slightly less efficient, as it creates an option and then can 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 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 matching solution, or equivalent with if, so you can reuse it for this particular case.)

+10
source

I would use filterNot here:

 scala> Option("hey").filterNot(_ == "NA") res0: Option[String] = Some(hey) scala> Option("NA").filterNot(_ == "NA") res1: Option[String] = None 

This requires you to think of Option as a collection with one or zero element, but if you get used to this habit, it is understandable enough.

+4
source

A simple and intuitive approach includes this expression,

 if (s.isEmpty) None else Some(s) 

This suggests that s denotes a value that would otherwise be matched (thanks to @RexKerr for the note).

0
source

Source: https://habr.com/ru/post/981628/


All Articles