简体   繁体   中英

Pattern matching java.lang.Long

I'm confused with scala pattern matching behaviour, see code below:

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

First two functions are ok, but third(useComplexJavaLong) throws scala.MatchError: 1 (of class java.lang.Long)

useComplexJavaLong only matches a single case where the remainder of the modolu operation is 0. What happens if the remainder isn't equal to 0? You get a MatchError since there is no case which handles that. In the case of your example, 1 % 1000 is equal to 1, not 0, and thus the pattern match blows up. You'll need an additional case:

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

Because the pattern matching in the method useCompleJavaLong is not complete. You can change it to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM