-1

I have the following code:

val obj: Int = 5;
var objType: Class[_] = obj.getClass

objType match {
          case _: Int =>
            byeBuffer.putInt(asInstanceOf[Int])

          case _: Long =>
            byeBuffer.putLong(asInstanceOf[Long])

          case _: Float =>
            byeBuffer.putFloat(asInstanceOf[Float])

          case _: Double =>
            byeBuffer.putDouble(asInstanceOf[Double])

          case _: Boolean => {
            val byte = if (asInstanceOf[Boolean]) 1 else 0
            byeBuffer.put(byte.asInstanceOf[Byte])
          }

          case default => throw new UnsupportedOperationException("Type not supported: " + default.getClass)
}

This code is broken. However if I used obj instead of objType then it would work. But I want to use specifically objType in the pattern matching.

Alon
  • 10,381
  • 23
  • 88
  • 152
  • 4
    Does this answer your question? [Pattern matching on Class\[\_\] type?](https://stackoverflow.com/questions/7519140/pattern-matching-on-class-type) – Duelist May 02 '20 at 15:42

1 Answers1

2

Try

val intClass     = classOf[Int]
val longClass    = classOf[Long]
val floatClass   = classOf[Float]
val doubleClass  = classOf[Double]
val booleanClass = classOf[Boolean]

objType match {
  case `intClass`     => 

  case `longClass`    => 

  case `floatClass`   => 

  case `doubleClass`  => 

  case `booleanClass` => 
}
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66