Nikita Volkov
Nikita Volkov

Reputation: 43309

How to test a value on being AnyVal?

Tried this:

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

and this:

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
                      ^

The message is very informative. I get that I can't use it, but what should I do?

Upvotes: 16

Views: 3589

Answers (2)

Rex Kerr
Rex Kerr

Reputation: 167871

I assume that your type is actually Any or you'd already know whether it was AnyVal or not. Unfortunately, when your type is Any, you have to test all the primitive types separately (I have chosen the variable names here to match the internal JVM designations for the primitive types):

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

This works, prints I, and does not give an incomplete match error.

Upvotes: 14

Thipor Kong
Thipor Kong

Reputation: 597

I assume you want to test if something is a primitive value:

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

Upvotes: 17

Related Questions