gpt4 book ai didi

scala - Scala 中的提取器冲突

转载 作者:行者123 更新时间:2023-12-05 00:56:48 26 4
gpt4 key购买 nike

代码:

  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, Int)] = if (number % divider == 0) Some(number/divider, 0) else None
// def unapply(divider: Double): Boolean = number % divider.toInt == 0

编译过程中出现错误:
 Star pattern must correspond with varargs or unapplySeq
case divisionOf15(f1, f2, _*) => println(s"$f1, $f2")
^

如果我取消注释这一行:
//    def unapply(divider: Int): Option[(Int, Int)] = if (number % divider == 0) Some(number/divider, 0) else None

我收到两个错误:
 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")
^

我做错了什么还是这是一个错误?这些提取器似乎是无辜的,不应相互冲突。

最佳答案

language specification没有说明 unapply 的并发存在和 unapplySeq .不过,它暗示了它们的相互排斥性:

an object which has a member method named unapply or unapplySeq

...

if the extractor object x does not have an unapply method, but it does define an unapplySeq method


This blog还指出:

Note: if both unapply and unapplySeq are defined only unapply is used.


因此,要么定义不同的提取器(在我看来,在您的情况下重载定义似乎并不明显!),或者使用 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")
}

关于scala - Scala 中的提取器冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com