Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

sockets - Kotlin Nested Use Function for Java try-with-resource

My goal is to auto-close Socket and OutputStream in try-catch block.

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
}

Just wondering if there's a better way than using nested use{} for my goal. Any suggestion would be appreciated.

question from:https://stackoverflow.com/questions/65949050/kotlin-nested-use-function-for-java-try-with-resource

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

Closing the returned OutputStream will close the associated socket.

(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/Socket.html#getOutputStream())

Therefore, it is sufficient to do:

printerSocket.getOutputStream().use {
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...