Expressive try…catch declarations
Kotlin is advertised as an extremely expressive language. However, it's one of the characteristics of the language that is not obvious in the beginning, especially if you are used to other languages such as Java or JavaScript. In order to present the language style more clearly, in this recipe, we are going to discover how to work with the try…catch
declaration in a Kotlin way, by treating it as an expression.
Getting ready
Let's consider the following Java code:
int value; try { result = parseInt(input); } catch (NumberFormatException e) { } finally { result = 0; }
It declares an int result
variable. Next, it tries to parse the string value to the integer with the Integer.parseInt()
function, and if it succeeds, it assigns the result to the value
variable. If the parseInt()
fails to parse the string, a default value of 0
is assigned to the value
variable.
How to do it...
- Invoke the
parseInt()
function in thetry…catch
declaration:
try { parseInt("fdsaa...