scala中的提取器冲突

前端之家收集整理的这篇文章主要介绍了scala中的提取器冲突前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
码:

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的并发存在.但它暗示了它们的相互排斥性:

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,_*)) => println(s"$f1,$f2")
}

猜你在找的Scala相关文章