Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of mathematical operator at start of line

Tags:

kotlin

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"?

like image 453
Charles Avatar asked Oct 28 '25 07:10

Charles


2 Answers

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.

like image 147
Andrew Churilo Avatar answered Oct 31 '25 02:10

Andrew Churilo


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:

  • Put the whole expression on the one line.  (Which is unwieldy if it's long!)
  • Put the operator at the end of the previous line.  (Which is clearly what the language designers expect, but some of us find less logical and less clear.)
  • Prevent the first line from making sense on its own.

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…

like image 20
gidds Avatar answered Oct 31 '25 01:10

gidds