Hi Everyone, I'm quite new with Kotlin and KMP. I'...
# multiplatform
d
Hi Everyone, I'm quite new with Kotlin and KMP. I'm curious is there any equivalent for java.nio.ByteBuffer in KMP or other libraries that are compatible with KMP(serialization or ktor or something else). I need to wrap it around ByteArray and I do need to read/write Ints, Shorts, Longs, Floats etc.. Thanks in advance.
it used to have its own Buffer type, it's moving to kotlinx-io. Buffer is a bit more than you need (despite the similar name, it's a different set of functionality than nio buffers) but if you just need to put a ByteArray in and get Int etc. out, it'll do
🙌 1
m
You can use Kotlinx-IO, Ktor or Okio for this. The following examples take a ByteArray
bytes
and create a ShortArray
shorts
by reading short values from the buffer. With Kotlinx-IO it looks like this:
Copy code
Buffer().apply {
    write(bytes)
    shorts = ShortArray(NUM_VALUES) { readShort() }
}
With Ktor it looks like this:
Copy code
ByteReadChannel(bytes).apply {
    runBlocking {
        shorts = ShortArray(NUM_VALUES) { readShort() }
    }
}
With Ktor you have to deal with the fact that the read methods are suspending functions whereas in Kotlinx-IO they are not.