Scala Syntactic Sugar转换为`Option`

Vin*_*eng 6 scala

在Scala中工作时,我经常想要解析一个类型的字段[A]并将其转换为a Option[A],只有一个案例(例如,"NA""")被转换为None,而另一个案例被包装在一些中.

现在,我正在使用以下匹配语法.

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

有没有更简洁/惯用的方式来写这个?

Rex*_*err 10

有一种更简洁的方法.之一:

Option(x).filter(_ != "")
Option(x).filterNot(_ == "")
Run Code Online (Sandbox Code Playgroud)

虽然效率有点低,因为它会创建一个Option,然后可能会抛弃它.

如果你经常这么做,你可能想要创建一个扩展方法(或者只是一个方法,如果你不介意首先使用方法名称):

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

现在你可以

scala> 47.toString optNot ""
res1: Option[String] = Some(47)
Run Code Online (Sandbox Code Playgroud)

(当然,你总是可以创建一个方法,它的主体是你的匹配解决方案,或者是一个与if相同的方法,所以你可以在特定的情况下重用它.)