Best way to translate this java code into kotlin

前端 未结 3 537
后悔当初
后悔当初 2021-01-13 15:57
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream in = connection.getInputStream();
int bytesRead = 0;
         


        
3条回答
  •  感情败类
    2021-01-13 16:32

    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() }
    

    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
    }
    

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

提交回复
热议问题