Sorry, forgot different workspaces have different ...
# announcements
i
Sorry, forgot different workspaces have different sets of Enter/Shift+Enter preferences. Hello, I'm translating some Java code to Kotlin, and one function takes an
InputStream
and loops over it, reading fixed-size chunks of bytes from it. However, it uses the Java idiom where assignment is used as an expression:
Copy code
byte[] buffer = new byte[CHUNK_SIZE];
while ((bytesRead = stream.read(buffer, 0, CHUNK_SIZE)) != -1) {
    // do things
}
Kotlin, of course, does not like this, as assignments are not expressions. Is there an idiomatic way to iterate over sized chunks from a stream, like
lines
but less text-oriented? I could call
read
inside and outside the loop, but I'd like to avoid that if possible.
f
if you're uring JDK9+, I'd suggest just using the InputStream::readAllBytes function, otherwise Kotlin 1.3 seems to have added a
readBytes
extension on InputStreams that does the same thing but with a ByteArrayOutputStream
if you can't use those looks like you'll have to do the weird looking
while
unfortunetely
looks like that's what the
copyTo
extension is doing anyway:
Copy code
var bytes = read(buffer)
    while (bytes >= 0) {
        ...
        bytes = read(buffer)
    }
i
Yeah, the weird-looking while ended up looking less weird than I imagined it would. Thanks!
f
lol no problem