https://kotlinlang.org logo
#codereview
Title
# codereview
e

elect

05/09/2021, 5:52 AM
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

elect

05/09/2021, 6:59 AM
thanks for bringing that up, but it has already my vote 🙂 Interesting alternative, thanks
m

Michael Böiers

05/10/2021, 2:23 PM
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

ephemient

05/10/2021, 5:26 PM
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

Michael Böiers

05/10/2021, 5:35 PM
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

ephemient

05/10/2021, 5:46 PM
(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

Michael Böiers

05/11/2021, 6:16 AM
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.
10 Views