scala中的提取器冲突

时间:2016-02-28 15:52:50

标签: 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")
  }

如果我取消注释这些行:

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

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

1 个答案:

答案 0 :(得分:5)

language specification没有说明unapplyunapplySeq的并发存在。但它暗示了他们的相互排斥性:

  

具有名为unapplyunapplySeq

的成员方法的对象      

...

     

如果提取器对象 x 没有unapply方法,但确实定义了unapplySeq方法

This blog还声明:

  

注意:如果同时定义了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")
}