16

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?

Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169
  • Useful reads: [Scala Type Hierarchy](https://docs.scala-lang.org/tour/unified-types.html) and [Pattern matching](https://docs.scala-lang.org/tour/pattern-matching.html) – Ricardo Dec 27 '22 at 22:14

2 Answers2

17

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
Thipor Kong
  • 597
  • 3
  • 8
  • 6
    Or if you don't want to use the `null` trick: `def testAnyVal[T](x: T)(implicit m: Manifest[T]) = m <:< manifest[AnyVal]`. – Travis Brown May 02 '12 at 16:27
  • 4
    @TravisBrown - Or if you don't want to write an explicit manifest parameter, `def testAnyVal[T: Manifest](t: T) = manifest[T] <:< manifest[AnyVal]` – Rex Kerr May 02 '12 at 16:35
  • @Rex: Right, that's nicer—I was just sticking more closely to Thipor's formulation. – Travis Brown May 02 '12 at 16:39
14

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.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407