14

これを試しました:

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

この:

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
                      ^

メッセージは非常に有益です。使えないのですが、どうしたらいいですか?

4

2 に答える 2

17

何かがプリミティブ値であるかどうかをテストしたいと思います。

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
于 2012-05-02T16:02:19.020 に答える
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")
}

これは機能し、印刷Iされ、不完全な一致エラーは発生しません。

于 2012-05-02T16:34:08.970 に答える