'Kotlin try statement not working when specifying if without else
Why would this piece of Kotlin code not compile? Needless to say return type is Unit (or void in Java)
The error is: 'if' must have both main and 'else' branches if used as an expression
fun test() =
try {
if (true) {
}
// no else clause
} finally {
print("")
}
It doesn't matter which combination of the try statement I implement (try with catch or try with finally or all of them)
fun test() =
try {
if (true) {
}
// no else clause
} catch (e: Exception) {
print("")
} finally {
print("")
}
Strangely this compiles:
fun test() =
try {
if (true) {
}
print("print something")
} catch (e: Exception) {
print("")
} finally {
print("")
}
Using latest IntelliJ.
Solution 1:[1]
try/catch/finally, when, and if/else can be used either as a statement or as an expression. When used as an expression, they have to return something. You are forcing the compiler to treat it as an expression by putting = in front of it.
You return something in try/catch by making it the last thing in your try block and in any catch blocks.
if by itself cannot be an expression. It has to be followed by else to be an expression.
Since the if block is the last thing in your try clause of your try/catch expression, it has to be an expression, because the last thing in the block represents what it returns.
The compiler is complaining because the last thing in your try/catch expression's try block is not an expression. It's an if statement.
When you add println() at the end, that's an expression, so it can be interpreted fine by the compiler. println() evaluates to Unit.
As @Gidds says in the comment below, the whole issue stems from making this a expression in the first place. If you have nothing useful to return (Unit), then make it a statement so you don't have to worry about pleasing the compiler. When you try to make it an expression, the compiler is pedantic because it's trying to prevent you from writing something that doesn't make sense to write if you're trying to return something useful.
Also, if you deliberately express that your expression should evaluate to Unit using : Unit =, then the compiler doesn't enforce that it really has to evaluate as an expression.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
