How to test a value on being AnyVal?

后端 未结 2 1558
小蘑菇
小蘑菇 2020-12-30 05:21

Tried this:

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


        
相关标签:
2条回答
  • 2020-12-30 05:37

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题