any better way than duplicate code like this? (I'm...
# codereview
e
any better way than duplicate code like this? (I'm receive a json response in 1 line, I want to loop char by char to properly display it for debug with the right new lines and indentations)
Copy code
var c = it.read() // it: InputStream
        while (c != -1) {
            ..
            c = it.read()
        }
Copy code
while(true){
  val c = it.read()
  if(c == -1) break
  ..
}
I still miss the java way, though 😐
another alternative:
Copy code
generateSequence { it.read() }.takeWhile { it != -1 }.forEach { c ->
    // ...
}
e
thanks for bringing that up, but it has already my vote 🙂 Interesting alternative, thanks
m
Nice! Makes sense as an extension function.
Copy code
import java.io.ByteArrayInputStream
import java.io.InputStream

fun InputStream.asCharSequence() = generateSequence { read() }
    .takeWhile { it != -1 }
    .map { it.toChar() }

val a = ByteArrayInputStream("foo".toByteArray())

a.asCharSequence().forEach { c -> println(c) }
(wrap with a Reader first if character conversion can be an issue)
e
you're not doing any character (en|de)coding there so I think a CharSequence is misleading...
InputStream.asByteSequence()
and
Reader.asCharSequence()
would be better
m
Yes, hence my comment after I had posted the code.
I wonder whether there‘s something in NIO which would do this out of the box ...
e
(byte|char)-at-a-time is not a great way to work with files and NIO doesn't really support it (APIs are geared towards reading/writing buffers)
m
Of course there are better ways to do it. If it’s a small file I would read it into a String and process it from there. If it’s about the indentation, going line by line with a BufferedReader would also be an option. Ultimately I would question Giuseppe’s requirement of being able to reproduce the exact formatting of the JSON. Either use a proper JSON parser to extract the contents, or don’t look at the content at all and just pass it on.