What would be a `runCatching`-equivalent of the `t...
# getting-started
v
What would be a
runCatching
-equivalent of the
try {} finally {}
code in Java? Is it what the
recover{}
function does?
j
For
Closeable
resources there is a
use
function. Otherwise it's ad-hoc, AFAIK.
h
The Kotlin equivalent of
try {} finally {}
in Java is
try {} finally {}
: •
runCatching
wraps the result in, well, a
Result
(which
try … finally
doesn't do, especially not in Java, where it's not even an expression). •
recover
is more like a
catch (Throwable t) { }
in Java, giving you the opportunity to do something with the exception and still give a
Result
back
v
@Joffrey how to use this
use
fun?
h
Example:
Copy code
FileWriter("test.txt")
  .use { it.write("something") }
Even if the
write
fails, the
FileWriter
will be closed. Works with every
Closable
resource.
v
Thanks, Henning. In my project the code in
finally
block is not used on
Closable
. So, probably a mis-use of the
finally
in my cause
h
Not necessarily, it just means
use
is not applicable to your problem.
3