Java try-with-resource的Kotlin嵌套使用函数 [英] Kotlin Nested Use Function for Java try-with-resource
问题描述
我的目标是在try-catch块中自动关闭 Socket
和 OutputStream
.
My goal is to auto-close Socket
and OutputStream
in try-catch block.
在通过Java搜索和学习 try-with-resouce 之后,我最终使用了 use {}
.但是,似乎无法避免嵌套 use {}
:
After searching and learning from Java try-with-resouce, I ended up using use{}
in Kotlin. However, it seems like nested use{}
cannot be avoided:
suspend fun print(): LoadingStatus {
var status = LoadingStatus.LOADING
withContext(Dispatchers.IO) {
try {
val printerSocket = Socket("192.168.x.xxx", 9100)
printerSocket.use { socket -> <- first use{}
socket.getOutputStream().use { <- second use{}
it.write("xxx".toByteArray())
status = LoadingStatus.DONE
}
}
} catch (e: IOException) {
Log.e("print()", "Printing Failed: please check your network")
status = LoadingStatus.ERROR
}
}
return status
}
只是想知道是否有比使用嵌套的 use {}
更好的方法.任何建议将不胜感激.
Just wondering if there's a better way than using nested use{}
for my goal. Any suggestion would be appreciated.
推荐答案
在 Socket
及其 OutputStream
的这种特殊情况下,不必使用在
,因为 Socket
和 OutputStream
上都使用 Socket.getOutputStream()
的约定规定:
In this particular case of a Socket
and its OutputStream
, it is unnecessary to use
on both the Socket
and the OutputStream
, because the contract of Socket.getOutputStream()
states that:
关闭返回的OutputStream将关闭关联的套接字.
Closing the returned OutputStream will close the associated socket.
Therefore, it is sufficient to do:
printerSocket.getOutputStream().use {
...
}
这篇关于Java try-with-resource的Kotlin嵌套使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!