Best way for Iteration & extract data on an IndexedSeq in scala

What is the best way to iterate and extract the data in scala with an indexedseq were there are indexed specific data

val data
=IndexedSeq(0x00,0x0F,0x33,0x35,0x35,0x35,0x36,0x35,0x30,0x37,0x31,0x33,0x30,0x38,0x31,0x30,0x33,0x43,0x4D,0x54,0x4D,0x31,0x2E,0x30,0x30,0x32)

Device Sends Connection command having length 14 bytes.

00 0F 33 35 35 35 36 35 30 37 31 33 30 38 31 30 33 43 4D 54 4D 31 2E 30 30 32

Header-2 Bytes Device ID 16 Bytes Firmware version 8 Bytes

I tried below for a manual check on each index

if(data(0)==0x00 && data(1)==0x0F){
  //New Connection

  val deviceId=(data.slice(2,17).map(_.toChar)).mkString
  val firmwareVersion=(data.slice(18,25).map(_.toChar)).mkString

  println(deviceId)
  println(firmwareVersion)
}

1 answer

  • answered 2018-11-08 11:14 pme

    You could use pattern matching:

    val data = Seq(0x00,0x0F,0x33,0x35,0x35,0x35,0x36,0x35,0x30,0x37,0x31,0x33,0x30,0x38,0x31,0x30,0x33,0x43,0x4D,0x54,0x4D,0x31,0x2E,0x30,0x30,0x32)
    
    data match {
      case 0x00::0x0F::xs => 
        val deviceId=(xs.take(15).map(_.toChar)).mkString
        val firmwareVersion=(data.slice(18,25).map(_.toChar)).mkString
        println(deviceId)
        println(firmwareVersion)
      case other => // handle unexpected data
    }