2012-05-02 14 views
12

provato questo:Come testare un valore su AnyVal?

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

e questo:

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 
        ^

Il messaggio è molto istruttiva. Capisco che non posso usarlo, ma cosa dovrei fare?

risposta

12

Presumo che si desidera verificare se qualcosa è un valore di base:

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

Oppure se non si desidera utilizzare il trucco 'null':' def testAnyVal [T] (x: T) (implicito m: Manifest [T]) = m <:

+3

@TravisBrown - O se non si desidera scrivere un parametro manifest esplicito, 'def testAnyVal [T: Manifest] (t: T) = manifest [T] <:

+0

@Rex: Right, è più bello - stavo semplicemente attaccando più strettamente alla formulazione di Thipor. –

12

Presumo che il tipo è in realtà Any o si aveva già sapeva se fosse AnyVal o no. Purtroppo, quando il tipo è Any, è necessario testare tutti i tipi primitivi separatamente (ho scelto i nomi delle variabili qui per abbinare le designazioni JVM interni per i tipi primitivi):

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

Questo funziona, stampe I, e non fornisce un errore di corrispondenza incompleto.

Problemi correlati