Pattern matching in Scala

bigint, pattern-matching, scala

Solution

`match` is more specific than equality; you can't just be equal, you must also have the same type.

In this case, `BigInt` is not a case class and does not have an `unapply` method in its companion object, so you can't match on it directly. The best you could do is

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

or some variant thereof (e.g. `case ab if (ab == (1,5)) =>`).

Alternatively, you could create an object with an unapply method of appropriate type:

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

Problem

``` 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 ^ ``` Can someone perhaps explain me how to pattern match here?

Original source

Related problems