How to convert a Data Class to ByteBuffer in Kotlin?

N. S. Mehra picture N. S. Mehra · Feb 7, 2019 · Viewed 9.2k times · Source

I am trying to use Kinesis, which expects data in byte buffer format. All the examples I have seen so far are in Java and pass simple strings. Can anybody give an idea of how to convert a kotlin data class to bytebuffer?

e.g. data class abc ( var a: Long, var b: String, var c: Double )

Answer

Jarvis picture Jarvis · Feb 7, 2019

Check the below method

fun toByteArray(): ByteArray? {
val size: Int = 8 + 8 + string.Size

val byteBuffer = ByteBuffer.allocate(size)
        .put(long) //long veriable 
        .put(double) // double veriable 
        .put(string)


   return byteBuffer.array()
}

You can allocate the size based on dataType size like Int 4 bytes, Double and Long 8 bytes

for reading back to dataType

  val byteBuffer = ByteBuffer.wrap(byteArray)
        byteBuffer.get(Int) //Int variable
        byteBuffer.get(Double) //Double variable
        byteBuffer.get(nonce)