qed*_*qed 4 scala pattern-matching
码:
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")
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释这些行:
// 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
Run Code Online (Sandbox Code Playgroud)
编译期间出现错误:
Star pattern must correspond with varargs or unapplySeq
case divisionOf15(f1, f2, _*) => println(s"$f1, $f2")
^
Run Code Online (Sandbox Code Playgroud)
如果我取消注释这一行:
// def unapply(divider: Int): Option[(Int, Int)] = if (number % divider == 0) Some(number/divider, 0) else None
Run Code Online (Sandbox Code Playgroud)
我收到两个错误:
scrutinee is incompatible with pattern type;
found : Int
required: Float
case divisionOf15(f1, f2, _*) => println(s"$f1, $f2")
^
Star pattern must correspond with varargs or unapplySeq
case divisionOf15(f1, f2, _*) => println(s"$f1, $f2")
^
Run Code Online (Sandbox Code Playgroud)
我做错了什么或这是一个错误?这些提取器似乎是无辜的,不应该相互冲突.
该语言规范并没有说明的同时存在任何unapply和unapplySeq.但它暗示了它们的相互排斥性:
具有名为
unapply或的成员方法的对象unapplySeq...
如果提取器对象x没有
unapply方法,但它确实定义了一个unapplySeq方法
这篇博客还指出:
注意:如果同时定义了unapply和unapplySeq,则仅使用unapply.
所以要么定义不同的提取器(对我来说,在你的情况下重载定义似乎不太明显!),或者去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, f2, _*)) => println(s"$f1, $f2")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |