Scala中的模式匹配

5 scala pattern-matching bigint

scala> (1,5) == BigInt(12) /% 7
res3: Boolean = true

scala> BigInt(12) /% 7 match {
 | case (1,5) => true
 | }

<console>:9: error: type mismatch;
found   : Int(1)
required: scala.math.BigInt
          case (1,5) => true
                ^
Run Code Online (Sandbox Code Playgroud)

也许有人可以在这里解释我如何模式匹配?

Rex*_*err 9

match比平等更具体; 你不能只是平等,你也必须拥有相同的类型.

在这种情况下,BigInt不是案例类,并且unapply在其伴随对象中没有方法,因此您无法直接匹配它.你能做的最好的是

  BigInt(12) /% 7 match {
    case (a: BigInt,b: BigInt) if (a==1 && b==5) => true
    case _ => false
  }
Run Code Online (Sandbox Code Playgroud)

或其某些变体(例如case ab if (ab == (1,5)) =>).

或者,您可以使用适当类型的unapply方法创建对象:

object IntBig { def unapply(b: BigInt) = Option(b.toInt) }

scala> BigInt(12) /% 7 match { case (IntBig(1), IntBig(5)) => true; case _ => false }
res1: Boolean = true
Run Code Online (Sandbox Code Playgroud)