Scala可选模式匹配

时间:2016-12-29 04:06:54

标签: scala pattern-matching

我发现自己经常使用模式匹配,返回Option,其中无匹配大小写返回None,例如

x match {
    case A(a) => Some(a)
    case B(b) => Some(b)
    case _ => None
}

我可以想象使用

简化这个
object MaybeMatchImplicits {
    implicit class MaybeMatcher[A](val underlying: A) extends AnyVal {
        @inline 
        def maybeMatch[B](f: PartialFunction[A, B]): Option[B] = f.lift.apply(underlying)
    }
}

允许

scala> import MaybeMatchImplicits._
import MaybeMatchImplicits._

scala> 5 maybeMatch { case 5 => 'good }
res0: Option[Symbol] = Some('good)

scala> 6 maybeMatch { case 5 => 'good }
res1: Option[Symbol] = None

我想知道这种方法是否隐藏了任何陷阱和/或是否在Scala 2.11+中有更简单/更好/更惯用的机制。

更新:目标是处理匹配项的rhs上的任意计算,这使得基于异常的解决方案不合需要。

3 个答案:

答案 0 :(得分:6)

习语:

scala> case class A(a: Int) ; case class B(b: String)
defined class A
defined class B

scala> def f(x: Any) = Option(x) collect { case A(a) => a ; case B(b) => b }
f: (x: Any)Option[Any]

scala> f(42)
res0: Option[Any] = None

scala> f(A(42))
res1: Option[Any] = Some(42)

scala> f(B("ok"))
res2: Option[Any] = Some(ok)

可替换地:

scala> import PartialFunction.{cond => when, condOpt => whenever}
import PartialFunction.{cond=>when, condOpt=>whenever}

scala> def f(x: Any) = whenever(x) { case A(a) => a ; case B(b) => b }
f: (x: Any)Option[Any]

scala> f(42)
res3: Option[Any] = None

scala> f(A(42))
res4: Option[Any] = Some(42)

scala> f(B("ok"))
res5: Option[Any] = Some(ok)

答案 1 :(得分:2)

从选项中收集

使用get方法(参见下面给出的实现),它围绕选项包装给定值,然后收集所需的值。

使用选项换行值,然后收集您想要收集的内容。

Option(x: Any).collect { case 1 => 1 }

x get { case 2 => 2 } // get implementation is given below

Scala REPL

scala> Option(1).collect { case 1 => 1 }
res0: Option[Int] = Some(1)

scala> Option(2).collect { case str: String => "bad" }
<console>:12: error: scrutinee is incompatible with pattern type;
 found   : String
 required: Int
       Option(2).collect { case str: String => "bad" }
                                     ^

scala> Option(2: Any).collect { case str: String => "bad" }
res2: Option[String] = None

scala> Option(2: Any).collect { case 2 => "bad" }
res3: Option[String] = Some(bad)

使用隐式类

的Nicer API
implicit class InnerValue[A](value: A) {
  def get[B](pf: PartialFunction[Any, B]): Option[B] = Option(value) collect pf
}

Scala REPL

scala> implicit class InnerValue[A](value: A) {
     |   def get[B](pf: PartialFunction[Any, B]): Option[B] = Option(value) collect pf
     | }
defined class InnerValue

scala> 2.get { case 2 => 2}
res5: Option[Int] = Some(2)

scala> 2.get { case 3 => 2}
res6: Option[Int] = None

现在你可以invoke获取方法并传递部分函数。现在,您可能会获得包含在Some中的值,或者将获得None。

请注意,上述API(get方法)不是类型安全的,您可以

 2.get { case str: String => str }

返回无。

现在,如果你想要类型安全,请进行以下更改

类型安全

 implicit class InnerValue[A](value: A) {
  def get[B](pf: PartialFunction[A, B]): Option[B] = Option(value) collect pf
 }

请注意,在partial函数中,输入参数类型为A而不是Any。

现在,当你做

2.get { case str: String => str }

您将收到编译错误。

scala>      2.get { case str: String => str }
<console>:15: error: scrutinee is incompatible with pattern type;
 found   : String
 required: Int
            2.get { case str: String => str }

解决编译错误

您可以通过执行以下操作来解决编译错误

scala> (2: Any) get { case str: String => str}
res16: Option[String] = None

答案 2 :(得分:0)

我会这样做:

def trial(a:Any, f:Any => Any) = try Some(f(a)) catch {case _:MatchError => None}

implicit class BetterAny(a:Any) {
   def betterMatch(f:Any => Any) = trial(a, f)
}

// some example classes
case class A(i:Int)
case class B(s:String)

在REPL上:

scala> A(1) betterMatch {case A(a) => a; case B(b) => b}
res11: Option[Any] = Some(1)

scala> 2 betterMatch {case A(a) => a; case B(b) => b}
res12: Option[Any] = None