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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…