Saturday 1 June 2024

Expressions, Declarations, Statements

"What's de difference between expression and statement?" is a typical question with a simple answer: An expression evaluates to a value (produces a value). A statement does something. All expressions are (can be used as) statements, but not all statements are (can be used as) expressions. As expressions produce a value you can use them on the right side of an assignment, as a parameter to a function, in a condition...

There's an additional item to take into account declarations. I think that we can say that declarations are statements that "declare" something (declare a class, a function, an enum, a variable...)

As modern commonly used languages feature richer syntaxes, there are more things to take into account. Things that in older languages were just statements, not expressions, in these rich languages are expressions. In Kotlin we have if-else expressions (well, that's nothing too impressive, it's just the equivalent to the ternary operator), when (switch) expressions, try-catch expressions, throw and return expressions.

When I first came across this "almost everything is an expression" Kotlin feature I was pretty amazed, and I read here something that explains it, but that I've now realised that is not fully accurate.

In Kotlin nothing is just a statement. Every statement is either a declaration or a expression.

But as I've said, that's not fully correct. In Kotlin there are 2 things that are not expressions and are not declarations either: loops and assignments. This is a great read.

Kotlin does not explicitly distinguish between statements, expressions and declarations, i.e., expressions and declarations can be used in statement positions.

It's interesting to note that JavaScript lacks these nice try-catch, switch, throw, return expressions... but on the other hand features class expressions (named and unnamed) and function expressions (named and unnamed) while in Kotlin we don't have class expressions at all, and we have anonymous function expressions, but not named ones.

It's also interesting that the 2 things that in Kotlin are neiter expressions nor declarations, but only statements (loops and assignments), in Python (that unfortunately has a much less rich syntax) can be used as expressions. for expressions correspond to list-generator comprehensions, and assignment expressions correspond to the walrus operator :=.

No comments:

Post a Comment