简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM