Would let
expressions be a good fit for Scala? I haven’t found evidence for this being proposed already, which is surprising. If it has been, let me know!
Full description, and a limited implementation (as a compiler plugin) are here: https://github.com/jeremyrsmith/let-plugin
TLDR - Allow these:
val result = let (x = expr1(), y = expr2()) in resultExpr(x, y)
val result = let {
x = expr1()
y = expr2()
} in resultExpr(x, y)
A minimal motivating example (excerpted from above link):
def wizzle(a: Int, b: Int) = {
val temp = foo(a, b)
bar(temp, baz(temp))
}
We had to pass the result of foo
to two different functions, so we assigned it to a value. This is perfectly fine and great.
Except, the body of wizzle
is no longer an expression, syntactically speaking. It’s now a Block
(in Scala AST terms), which is a list of “stats” and a result expression. The fact that it isn’t syntactically an expression can be witnessed by the fact that the curly braces surrounding it cannot be removed.
It’s better[citation needed?] to use expressions everywhere. Certainly from a functional programming standpoint, if everything is an expression you can be reasonably assured of purity (until a method is called which is not an expression).
However, using a val
doesn’t mean it isn’t semantically an expression, because it can be trivially transformed into one - even with existing Scala syntax:
def wizzle(a: Int, b: Int) = foo(a, b) match {
case temp => bar(temp, baz(temp))
}
Here, the braces have been eliminated, and we know we have an expression from a syntactic perspective.
But this misappropriation of match
is misleading - we aren’t doing any pattern matching; only naming the result of foo
so that it can be referenced multiple times in a nested expression.
This is why a let
expression would be great:
def wizzle(a: Int, b: Int) = let (temp = foo(a, b)) in bar(temp, baz(temp))
All three versions of wizzle
are semantically equivalent. But the third example, which is what this plugin enables, allows wizzle
to be specified as an expression without a confusing use (misuse?) of match
.
Some arguments against:
- No more keywords, please
- No more syntax sugar, please
- Using
val
s is clearer anyway. People don’t care about syntactic expression-ness.