So I've just started using Kotlin for Android, and converted my Android Java codes into Kotlin.
In one of the conversions, I stumbled upon a BufferedReader, which I would usually write in Java as the following:
String result = ""; String line = ""; BufferedReader reader = new BufferedReader(someStream); while ( (line = reader.readLine()) != null ) { result += line; }
But in Kotlin, it seems that Kotlin doesn't allow me to assign values to variables in while conditions.
Currently, I've written the code as the following:
val reader = BufferedReader(someStream) var line : String? = "" while (line != null) { line = reader.readLine() result += line }
which I don't find so elegant and feels prev-gen, despite using Kotlin.
What would be the best way to use BufferedReader in Kotlin?
A buffered character-input stream that keeps track of line numbers. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
1) Select "Project" from the top of the vertical toolbar to open the project "tool window" 2) From the drop-down menu at the top of the "tool window", select "Android" 3) Right-click on "App" and select "New" then -> "Folder" (the one with the green Android icon beside it) then -> "Assets Folder" 4) Right-click on the ...
If you still wanted to read it line by line you could use some extension functions from std lib and do it as follows:
val reader = someStream.bufferedReader() val iterator = reader.linesSequences().iterator() while(iterator.hasNext()) { val line = iterator.next() // do something with line... } reader.close()
or alternatively, using a "functional" approach:
val reader = someStream.bufferedReader() reader.useLines { it.map { line -> // do something with line } }
by using useLines, you don't need to explicitly call close on the reader, the useLines extensions function will do it for you!
Just adding those for reference.. cheers
You can use bufferedReader
like so
val allText = inputStream.bufferedReader().use(BufferedReader::readText)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With