如何测试AnyVal的值?

Nik*_*kov 13 scala

试过这个:

scala> 2.isInstanceOf[AnyVal]
<console>:8: error: type AnyVal cannot be used in a type pattern or isInstanceOf test
              2.isInstanceOf[AnyVal]
                            ^
Run Code Online (Sandbox Code Playgroud)

还有这个:

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
                      ^
Run Code Online (Sandbox Code Playgroud)

这条消息非常有用.我知道我不能使用它,但我该怎么办?

Thi*_*ong 16

我假设您想测试某些东西是否是原始值:

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
Run Code Online (Sandbox Code Playgroud)

  • 或者如果你不想使用`null`技巧:`def testAnyVal [T](x:T)(隐式m:Manifest [T])= m <:<manifest [AnyVal]`. (6认同)
  • @TravisBrown - 或者如果你不想写一个明确的清单参数,`def testAnyVal [T:Manifest](t:T)= manifest [T] <:<manifest [AnyVal]` (4认同)

Rex*_*err 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")
}
Run Code Online (Sandbox Code Playgroud)

这可以工作,打印I,并且不会给出不完整的匹配错误.