I have a basic question for my general knowledge of Kotlin concerning the mathematical operators:
I was writing an equation and I mistakenly put the plus sign on the second line which caused my equation not to work as on the examples below:
val x = 2 + 3 //x = 5 CORRECT
val x = 2 +
    3 //x = 5 CORRECT
val x = 2
    + 3 //x = 2 WRONG
My question is: why Kotlin is not showing any error message on the last example? How is Kotlin interpreting the line "+3"?
val x = 2 is correct expression, so compiler uses it as complete expression.
+ 3 is correct expression although it doing nothing.
val x = 2 + is uncompleted expression - the compiler is trying to complete it using the next line.
This is an unfortunate result of the way Kotlin assumes a semicolon at the end of lines.
In languages like Java, every statement must end with a semicolon, so there's no ambiguity.
Kotlin allows you to omit semicolons, which can be handy. But it's a bit over-eager: it infers one at the end of every line that would make sense on its own, ignoring the following lines. This is rather annoying to those of us who like to put operators at the start of a line, not the end…
Most of the time, the following line won't make sense on its own, so you get a compiler error to warn you of the issue.  Unfortunately, you've found one of the rare cases where the following line is valid, and so there's no error!  (Kotlin has a unary plus to match its unary minus, so +3 is a number just like -4.  And a number on its own is a valid expression.  Kotlin calculates the value, and then discards it.)
The solutions are:
The best way I've found to do that last one is with parens:
val x = (2
         + 3)
It looks awkward in a very short expression, but it works reasonably well on longer ones — not ideal, but necessary unless/until Kotlin gets smarter about where to assume semicolons…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With