Best way to use BufferedReader in Kotlin

Akira Kido picture Akira Kido · Dec 6, 2016 · Viewed 21.3k times · Source

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?

Answer

miensol picture miensol · Dec 6, 2016

You can use bufferedReader like so

val allText = inputStream.bufferedReader().use(BufferedReader::readText)