试过这个:
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)
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,并且不会给出不完整的匹配错误.
| 归档时间: |
|
| 查看次数: |
2688 次 |
| 最近记录: |