scala中的提取器冲突
发布时间:2020-12-16 18:08:27 所属栏目:安全 来源:网络整理
导读:码: case class Division(val number: Int) {// def unapply(divider: Int): Option[(Int,Int)] = if (number % divider == 0) Some(number/divider,0) else None// def unapply(divider: Double): Boolean = number % divider.toInt == 0 def unapplySeq(x
码:
case class Division(val number: Int) { // def unapply(divider: Int): Option[(Int,Int)] = if (number % divider == 0) Some(number/divider,0) else None // def unapply(divider: Double): Boolean = number % divider.toInt == 0 def unapplySeq(x: Float): Option[Seq[Int]] = { val seq = (3 to 10).map(i => i * x.toInt) println(seq) Some(seq) } } val divisionOf15 = Division(15) // val y = 5 match { // case divisionOf15(z,w) => println(s"$z,$w") // case _ => println(s"Not divisible") // } // val z = 5.0 match { // case divisionOf15() => println("Divisible") // case _ => println("Not divisible") // } val u = 5.0F match { case divisionOf15(f1,f2,_*) => println(s"$f1,$f2") } 如果我取消注释这些行: // def unapply(divider: Int): Option[(Int,0) else None // def unapply(divider: Double): Boolean = number % divider.toInt == 0 编译期间出现错误: Star pattern must correspond with varargs or unapplySeq case divisionOf15(f1,$f2") ^ 如果我取消注释这一行: // def unapply(divider: Int): Option[(Int,0) else None 我收到两个错误: scrutinee is incompatible with pattern type; found : Int required: Float case divisionOf15(f1,$f2") ^ Star pattern must correspond with varargs or unapplySeq case divisionOf15(f1,$f2") ^ 我做错了什么或这是一个错误?这些提取器似乎是无辜的,不应该相互冲突. 解决方法
language specification没有说明unapply和unapplySeq的并发存在.但它暗示了它们的相互排斥性:
This blog还指出:
所以要么定义不同的提取器(对我来说,在你的情况下重载定义似乎不太明显!),或者使用unapply: case class Division(val number: Int) { def unapply(divider: Int): Option[(Int,Int)] = if (number % divider == 0) Some(number/divider,0) else None def unapply(divider: Double): Boolean = number % divider.toInt == 0 def unapply(x: Float): Option[Seq[Int]] = { val seq = (3 to 10).map(i => i * x.toInt) println(seq) Some(seq) } } val u = 5.0F match { case divisionOf15(Seq(f1,_*)) => println(s"$f1,$f2") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |