2017-02-16 39 views
2

我感到困惑與階模式匹配行爲,參見下面的代碼:模式匹配java.lang.Long中

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(的class java.lang.Long)

回答

3

useComplexJavaLong只匹配一個情況,其中modolu操作的剩餘部分爲0.如果餘數不等於0,會發生什麼情況?你得到MatchError,因爲沒有任何情況可以處理。在你的例子中,1 % 1000等於1,而不是0,因此模式匹配爆發。由於該方法useCompleJavaLong匹配模式是不完整的

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

:你需要一個額外的案例。您可以將其更改爲

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