Extractor errors in scala

the code:

  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")
  }

If I uncomment these lines:

//    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

An error occurs during compilation:

 Star pattern must correspond with varargs or unapplySeq
    case divisionOf15(f1, f2, _*) => println(s"$f1, $f2")
         ^

If I uncomment this line:

//    def unapply(divider: Int): Option[(Int, Int)] = if (number % divider == 0) Some(number/divider, 0) else None

I get two errors:

 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")
         ^

Am I doing something wrong or is it a mistake? These extractors seem innocent and should not conflict with each other.

+4
source share
1 answer

The language specification says nothing about the parallel presence of unapplyand unapplySeq. He hints at their mutual exclusivity, though:

an object that has a member method named unapplyorunapplySeq

...

if the extractor object x does not have a method unapply, but it defines a methodunapplySeq

This blog also says:

:, 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")
}
+5

All Articles