Vladislav Filinkov
07/03/2024, 7:32 AMSam
07/03/2024, 7:36 AMfinally block is Kotlin's built-in solution for this, so I'm not sure what you meanSam
07/03/2024, 7:36 AMuse function for Closeable resources, if you're looking for something more concise. But it just uses try-finally under the hood.Vladislav Filinkov
07/03/2024, 7:41 AMfinally i need to use try-catch . An if I do not want to catch any exception in same method - this will be ridiculous to catch exception and then throw it, just to get an access to finally. Did you really get a chance to look into the link that I shared?
fun foo() {
// do some logic, open some usb socket do something.
defer {
// close all connections
}
}
This is the idea, this is how they are doing thatgildor
07/03/2024, 7:42 AMSam
07/03/2024, 7:42 AMcatch to use finally? That's not true, you can use try with finally and no catch.Sam
07/03/2024, 7:43 AMfun foo() {
try {
doStuff()
} finally {
// close connections
}
}gildor
07/03/2024, 7:43 AMVladislav Filinkov
07/03/2024, 7:44 AMVladislav Filinkov
07/03/2024, 7:46 AMfun foo() {
try {
// do some logic, open some usb socket do something.
} finally {
// close all connections
}
}
This is what I want:
fun foo() {
// do some logic, open some usb socket do something.
defer {
// close all connections
}
}
Don’t you see that second option looks nicer?Sam
07/03/2024, 7:49 AMAlejandro Serrano.Mena
07/03/2024, 7:49 AMVladislav Filinkov
07/03/2024, 7:53 AMVladislav Filinkov
07/03/2024, 7:53 AMKlitos Kyriacou
07/03/2024, 8:36 AMdefer { block } in Swift translates directly to finally { block } in Kotlin, the only thing that's different is that you don't like the word try? I actually think it's helpful, as it immediately tells us that the enclosed code is subject to cleanup. Without try, as in Swift, we would have to scan the whole function to see if there was a finally (or defer) in that block.gildor
07/03/2024, 8:38 AMKlitos Kyriacou
07/03/2024, 8:45 AMdefer straight after each resource that you've opened, which is something you can't do with finally.CLOVIS
07/03/2024, 9:34 AMMichael Krussel
07/03/2024, 11:47 AMdefer is only the cleanup code is indented. With both try/finally and use the use of the resource goes into the {}. So it looks a little nicer, but the Kotlin code executes in the vertical order so it is probably easier to understand the execution order.