Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

java - Best way to use BufferedReader in Kotlin

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?

question from:https://stackoverflow.com/questions/41000584/best-way-to-use-bufferedreader-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use bufferedReader like so

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...