Skip to content

Is it possible to create a ByteArray of ByteArrays as elements in kotlin?

I have some issues with creating a ByteArray var where its elements are also ByteArray, I don’t know is it possible first ? and how to ?



A ByteArray is just what it sounds like, an array of bytes. If you want to hold onto multiple byte arrays you can use a generic list or array.

Something like this:

// say you have three byte arrays
val ba1 = ByteArray(3) { it.toByte() }
val ba2 = ByteArray(3) { (it + 3).toByte() }
val ba3 = ByteArray(3) { (it + 6).toByte() }

// make a list of them like so
val allByteArray = listOf(ba1, ba2, ba3)

Based on your more recent comment it seems you may want to add to allByteArray in a loop, if that is the case you can also use an ArrayList like this:

val allByteArray = ArrayList<ByteArray>()
for (i in 0 until 3) {
    // some byte array
    val ba = ByteArray(3) { (it + (i*3)).toByte() }

    // add to list

Also as suggested by Alexey Romanov, you could do this in the constructor for a MutableList (or the same thing can be done with a list if it doesn’t need to be mutable) like this:

val allByteArray = MutableList(3) { i ->
    ByteArray(3) { (it + (i*3)).toByte() }
User contributions licensed under: CC BY-SA
9 People found this is helpful