Sam Chen
Sam Chen

Reputation: 8847

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.

Upvotes: 0

Views: 959

Answers (1)

Raman
Raman

Reputation: 19585

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 {
  ...
}

Upvotes: 2

Related Questions