I want to build a List of Foo objects, each constructed by reading off a byte array starting from where the last Foo finished. Given that the only state needed when building are the contents so far and the number of bytes read, I was thinking of doing this by the repeated application of a function transforming a smaller List into a larger one. At each step the current List is passed as a parameter (and maybe the amount of bytes read so far to avoid re-parsing for this) and returned with an element appended. As this seems a pretty straightforward way to build up a List I was interested but unsuccessful in finding library functions that I could use for this. The following is the imperative example of what I am trying to do, I would like to make the functionality in bytesToList stateless and more concise:
def bytesToList(bytes: Array[Byte]): List[Foo] =
{
var numBytesRead = 0
var listToBuild = List[Foo]()
while (numBytesRead < bytes.length)
{
listToBuild ::= new Foo(bytes, numBytesRead)
numBytesRead += listToBuild.last.bytesRead
}
listToBuild
}
class Foo(bytesToRead: Array[Byte], startReadingAt: Int)
{val bytesRead = Random.nextInt(bytesToRead.length)}
If you can’t split the array up beforehand, you need to use explicit recursion, something like:
I don’t know how may Foos you’re expecting to have, but if it’s more than a thousand or so, it’s a good idea to make this tail recursive to avoid blowing up the stack (hint: add an extra parameter for the output, default value
Nil).