Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a value on being AnyVal?

Tags:

scala

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?

like image 923
Nikita Volkov Avatar asked May 02 '12 15:05

Nikita Volkov


1 Answers

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
like image 185
Thipor Kong Avatar answered Sep 29 '22 15:09

Thipor Kong