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
^
有人可以解释一下如何在这里进行模式匹配吗?
最佳答案
match
比相等更具体;你们不能只是平等,还必须有相同的类型。
在本例中,BigInt
不是一个 case 类,并且在其伴生对象中没有 unapply
方法,因此您无法直接匹配它。你能做的最好的就是
BigInt(12) /% 7 match {
case (a: BigInt,b: BigInt) if (a==1 && b==5) => true
case _ => false
}
或其某些变体(例如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
关于scala - Scala 中的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334237/