kotlin use函数

简述

  use函数是kotlin的语法糖,用于在使用资源(如文件、流等)后自动关闭它们。使用 use 函数可以确保资源在不再需要时被正确释放,从而避免资源泄漏和其他问题。

  和我们写try with resource是一样的,使用use会自动close资源

  use函数只能用于实现了 Closeable 接口的类

例子

  例如我们想写一个读取文件的方法,使用java写要:

public class Example {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("file.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  可以看到我们要捕捉很多异常,同时要手动关闭资源

  如果用kotlin来写,则简单许多

fun main() {
    val file = File("file.txt")
    file.bufferedReader().use { reader ->
        reader.forEachLine { line ->
            println(line)
        }
    }
}

  use函数会自动帮你捕捉异常,然后自动释放资源 

源码分析

  可以看到use函数内部帮你捕捉了异常,同时自动关闭调用者对象所属的资源

@InlineOnly
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    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
                }
        }
    }
}

 

posted @ 2023-04-25 16:20  艾尔夏尔-Layton  阅读(938)  评论(0编辑  收藏  举报