I'm a long-time Java developer turned onto Scala recently. I've stumbled across an interesting problem that I can't figure out how to solve without using a variable. I'm curious if it is possible.
My code is communicating with a remote device that has a CLI. Whenever I send a command, I need to read back all of the data from a java.io.InputStream for that socket until I see the prompt. The prompt isn't a fixed string, so I would like to use a regex to know when I encounter it. Note that the socket doesn't close, so I can't watch for the end of the stream. I also can't watch for new lines, because the prompt isn't followed by a return.
Now, one of the devices I was communicating with DID put a newline at the end of the prompt, so this was a cinch in Scala. I used a java.io.BufferedReader (named r) and this one liner did the job:
val responses = Stream.continually(r.readLine()).takeWhile(promptRegex.findFirstMatchIn(_).isEmpty)
Unfortunately my current device does not include a new line, so my call to readLine() never returns. I know I could make a stream that calls the read() method to read the stream byte-by-byte, but I can't look for a single character to know when I've hit my prompt.
I know I could solve this with a var, but I'd love to avoid it. I'm hopeful that there's a more functional way to solve this problem.
Thanks,
Joe