Initialize empty ByteArray

Viewed 7855

How do you initialize an empty ByteArray in Kotlin? Whenever I try to do this:

val asdfasdf : ByteArray

I get told that I need to initialize asdfasdf when I try to use it later here:

mVisualizer.getWaveForm(asdfasdf)

Variable 'asdfasdf' must be initialized

2 Answers

The easiest way to make a ByteArray in Kotlin in my opinion is to use byteArrayOf(). It works for an empty ByteArray, as well as one which you already know the contents of.

val nonEmpty = byteArrayOf(0x01, 0x02, 0x03)
var empty = byteArrayOf()
empty += nonEmpty

Your val asdfasdf : ByteArray is just declaration of immutable that needs to be initialized. If you know size in advance, you can init it like this val asdfasdf : ByteArray = ByteArray(10) however you probably need something like this val asdfasdf = arrayListOf<Byte>() to be able add items into it dynamically.

Related