Java try-with-resource的Kotlin嵌套使用函数 [英] Kotlin Nested Use Function for Java try-with-resource

查看:110
本文介绍了Java try-with-resource的Kotlin嵌套使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆