将此Java代码转换为Kotlin的最佳方法

问题描述:

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, 0, bytesRead);
}
out.close();

我对此部分特别好奇

while(bytesRead = in.read(buffer))

我们知道,在Kotlin中,asigements被当作语句处理,而在java中,asigements被当作表达式处理,因此这种构造仅在Java中是可能的.

We know that asigements are treated as statements in kotlin while in java they are treated as expressions, so this construct is only possible in java.

将此Java代码转换为kotlin的最佳方法是什么?

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

使用Kotlin的stdlib而不是直接翻译代码,它提供了许多有用的扩展功能.这是一个版本

Instead of translating the code literally, make use of Kotlin's stdlib which offers a number of useful extension functions. Here's one version

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

要回答原始问题:是的,赋值不视为表达式.因此,您需要将分配和比较分开.来看一下stdlib中的实现示例:

To answer the original question: You're right, assignments are not treated as expressions. Therefore you will need to separate the assignment and the comparison. Take a look at the implementation in the stdlib for an example:

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, 0, chars)
        charsCopied += chars
        chars = read(buffer)
    }
    return charsCopied
}

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