Как проверить, что Kotlin BufferedReader использует {return what} вызвал метод close ()? - PullRequest
0 голосов
/ 11 апреля 2020

Мой образец Kotlin о BufferedReader().use {} Интересно, вызывается ли close(), когда я возвращаюсь рано в блоке use

fun main() {
    sendGet()
}

fun sendGet() {
    val queryUrl = "http://www.google.com/search?q=kotlin&ie=utf-8&oe=utf-8"
    val url = URL(queryUrl)
    val conn = url.openConnection() as HttpURLConnection
    conn.requestMethod = "GET"
    conn.setRequestProperty("User-Agent", "Mozilla/5.0")

    val responseCode = conn.responseCode
    println("Response code: ${responseCode}")

    when (responseCode) {
        200 -> {
            println("response: ${conn.getResponseText()}")
        }
        else -> println("Bad response code: ${responseCode}")
    }

}

private fun HttpURLConnection.getResponseText(): String {
    BufferedReader(InputStreamReader(inputStream)).use {
        return it.readText()
    }
}

1 Ответ

3 голосов
/ 11 апреля 2020

Вы можете увидеть исходный код для use в stdlib, перейдя с помощью «Go к реализации» ( Cmd + B на Ma c):

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }
}

Поскольку вызов close находится внутри блока finally, он будет выполнен даже при досрочном возврате.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...