2012-05-02 14 views
12

嘗試這樣:如何測試作爲AnyVal的值?

scala> 2.isInstanceOf[AnyVal] 
<console>:8: error: type AnyVal cannot be used in a type pattern or isInstanceOf test 
       2.isInstanceOf[AnyVal] 
          ^

這:

scala> 12312 match { 
    | case _: AnyVal => true 
    | case _ => false 
    | } 
<console>:9: error: type AnyVal cannot be used in a type pattern or isInstanceOf test 
       case _: AnyVal => true 
        ^

的信息是非常豐富的。我知道我無法使用它,但我應該怎麼做?

回答

12

我假設你想測試,如果事情是一個原始值:

def testAnyVal[T](x: T)(implicit evidence: T <:< AnyVal = null) = evidence != null 

println(testAnyVal(1))     // true 
println(testAnyVal("Hallo"))    // false 
println(testAnyVal(true))     // true 
println(testAnyVal(Boolean.box(true))) // false 
+5

或者如果你不想使用'null'技巧:'def testAnyVal [T](x:T)(implicit m:Manifest [T])= m <:

+3

@TravisBrown - 或者如果你不想寫一個明確的清單參數,def testAnyVal [T:Manifest](t:T)= manifest [T] <:

+0

@Rex:Right,這更好 - 我只是更貼近Thipor的表述。 –

12

我假設你的類型實際上是Any或者你已經知道它是否是AnyVal與否。不幸的是,當你的類型爲Any,你必須單獨測試所有的原始類型(我選擇的變量名在這裏以匹配JVM內部代號爲基本類型):

(2: Any) match { 
    case u: Unit => println("Unit") 
    case z: Boolean => println("Z") 
    case b: Byte => println("B") 
    case c: Char => println("C") 
    case s: Short => println("S") 
    case i: Int => println("I") 
    case j: Long => println("J") 
    case f: Float => println("F") 
    case d: Double => println("D") 
    case l: AnyRef => println("L") 
} 

此作品,版畫I,並沒有給出不完整的匹配錯誤。

相關問題