模式匹配java.lang.Long

时间:2017-02-16 09:33:12

标签: scala pattern-matching scala-java-interop

我对scala模式匹配行为感到困惑,请参阅下面的代码:

import java.util.concurrent.atomic.AtomicLong

object LongPatternMatching {

  def main(args: Array[String]): Unit = {
    useJavaLong
    useScalaLong
    useComplexJavaLong
  }

  def useScalaLong: Unit = {
    val aLong: Long = Long.MaxValue
    aLong match {
      case v if v == Long.MinValue => println("min")
      case v if v == Long.MaxValue => println("max")
    }
  }

  def useJavaLong: Unit = {
    val aLong: java.lang.Long = java.lang.Long.MAX_VALUE
    aLong match {
      case v if v == java.lang.Long.MIN_VALUE => println("min")
      case v if v == java.lang.Long.MAX_VALUE => println("max")
    }

  }

  def useComplexJavaLong: Unit = {
    val counter: AtomicLong = new AtomicLong(0)
    counter.incrementAndGet() match {
      case count if count % 1000 == 0 => println(count)
    }
  }
}

前两个函数没问题,但是第三个(useComplexJavaLong)抛出scala.MatchError:1(类java.lang.Long)

2 个答案:

答案 0 :(得分:3)

useComplexJavaLong仅匹配单个情况,其中modolu操作的其余部分为0.如果余数不等于0,会发生什么?你得到MatchError因为没有处理它的情况。在您的示例中,1 % 1000等于1,而不是0,因此模式匹配会爆炸。您还需要一个案例:

def useComplexJavaLong: Unit = {
  val counter: AtomicLong = new AtomicLong(0)
  counter.incrementAndGet() match {
    case count if count % 1000 == 0 => println(count)
    case count => println(s"Remainder equals: ${count % 1000}")
  }
}

答案 1 :(得分:1)

因为方法useCompleJavaLong中的模式匹配不完整。您可以将其更改为

def useComplexJavaLong: Unit = {
    val counter: AtomicLong = new AtomicLong(0)
    counter.incrementAndGet() match {
      case count if count % 1000 == 0 => println(count)
      case other => println(other)
    }
  }