The best way to translate this java code into kotlin

URL url = new URL(urlSpec);
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream in = connection.getInputStream();
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
    out.write(buffer,bytesRead);
}
out.close();

I'm particularly curious about this part

while(bytesRead = in.read(buffer))

We know that in kotlin, asigements are regarded as statements, while in Java, they are regarded as expressions, so this structure can only be used in Java

What is the best way to translate this java code into kotlin?

Solution

Instead of translating the code literally, use kotlin's stdlib, which provides many useful extensions This is a version

val text = URL(urlSpec).openConnection().inputStream.bufferedReader().use { it.readText() }

Answer the original question: you are right. Homework is not regarded as expression Therefore, you need to separate allocation from comparison Take a look at the implementation example in stdlib:

public fun Reader.copyTo(out: Writer,bufferSize: Int = DEFAULT_BUFFER_SIZE): Long {
    var charsCopied: Long = 0
    val buffer = CharArray(bufferSize)
    var chars = read(buffer)
    while (chars >= 0) {
        out.write(buffer,chars)
        charsCopied += chars
        chars = read(buffer)
    }
    return charsCopied
}

Source: https://github.com/JetBrains/kotlin/blob/a66fc9043437d2e75f04feadcfc63c61b04bd196/libraries/stdlib/src/kotlin/io/ReadWrite.kt#L114

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>