Alon
Alon

Reputation: 11935

Scala pattern matching for type

I've written the following code:

array(0).getClass match {
  case Int.getClass =>
    byeBuffer = ByteBuffer.allocate(4 * array.length)

  case Long.getClass =>
    ByteBuffer.allocate(8 * array.length)

  case Float.getClass =>
    ByteBuffer.allocate(4 * array.length)

  case Double.getClass =>
    ByteBuffer.allocate(8 * array.length)

  case Boolean.getClass =>
    ByteBuffer.allocate(1 * array.length)

However the overuse of getClass feels clumsy to me.

Is there a nicer way to write it?

Upvotes: 1

Views: 168

Answers (1)

Andronicus
Andronicus

Reputation: 26076

You can omit the getClass and use the type operator (:):

val byteBuffer = array(0) match {
  case _: Int =>
    ByteBuffer.allocate(4 * array.length)
  case _: Long =>
    ByteBuffer.allocate(8 * array.length)
  case _: Float =>
    ByteBuffer.allocate(4 * array.length)
  case _: Double =>
    ByteBuffer.allocate(8 * array.length)
  case _: Boolean =>
    ByteBuffer.allocate(1 * array.length)
}

Also notice, that match is an expression in Scala, so you can move byteBuffer outside and assign the result to it. Such functional approach will make it cleaner and allow us to avoid reasigning to var and use val instead.

If you want to use the variable you're matching type against, then you can simply write for example l: Long and use the variable of type Long by the name l.

Upvotes: 4

Related Questions