Kotlin 之 AutoCloseable.use()

介绍 Kotlin 的一个语言特性:AutoCloseable.use()

Java try-with-resources

Java 7 之前,只能使用 finally 子句来关闭资源,所以代码不太优雅。举个例子:

1
2
3
4
5
6
7
8
9
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}

Java 7 引入了 try-with-resources 语句,它可以保证当前语句执行完毕后无论是否发生异常都能关闭资源。使用 try-with-resources 语句优化上述例子:

1
2
3
4
5
6
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}

不仅仅是 Java SDK 的内置资源(如 BufferedReader),任何实现了 java.lang.AutoCloseable 接口的资源都可以用在 try-with-resources 语句中。相当方便。

Kotlin AutoCloseable.use()

由于 Java 7 之后才支持 try-with-resources,所以 Kotlin 从 kotlin-stdlib-jre7kotlin-stdlib-jre8 两个新包开始提供 AutoCloseable.use() 功能。

由于 AutoCloseable.use() 只是一个简单的扩展方法,代码量少且很清晰,这里直接贴完整的源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Executes the given [block] function on this resource and then closes it down correctly whether an exception
* is thrown or not.
*
* @param block a function to process this [Closeable] resource.
* @return the result of [block] function invoked on this resource.
*/
@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 {
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
}
}
}
}

/**
* Closes this [Closeable], suppressing possible exception or error thrown by [Closeable.close] function when
* it's being closed due to some other [cause] exception occurred.
*
* The suppressed exception is added to the list of suppressed exceptions of [cause] exception, when it's supported.
*/
@SinceKotlin("1.1")
@PublishedApi
internal fun Closeable?.closeFinally(cause: Throwable?) = when {
this == null -> {}
cause == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}

简单总结关键点:

  • 不同于 Java 7 中,try-with-resources 语句只对实现 AutoCloseable 接口的资源生效,Kotlin 中任何实现 Closeable 接口的资源都会被自动关闭
  • use() 是扩展方法,它接收一个 block 对象,block 对象将 receiver (被扩展的那个对象) 作为参数。block 对象返回另一个类型为 R 的对象
  • use() 方法最终会返回 block 对象的返回值

看个例子:

1
2
3
4
5
fun getBitmap(): Bitmap {
return assets.open("sample.png").use {
return BitmapFactory.decodeStream(it)
}
}

对照着 AutoCloseable.use() 扩展方法来解读上面的例子:

  • assets.open() 返回一个 InputStream 实例
  • InputStream 类实现了 AutoCloseable 接口(AutoCloseableCloseable 的子类),所以可以对其应用 use() 扩展方法
  • { return BitmapFactory.decodeStream(it) } 作为 block 对象传给 use() 方法
  • block 对象将 it (itreceiver) 解码成 Bitmap,并且返回该 Bitmap 对象
  • getBitmap() 返回 block 对象返回的 Bitmap

参考