Can we circle back to why we actually need special syntax for higher order methods? A lambda argument is just an argument, just like a
, "foo"
, Some(42)
. How do we pass arguments to functions or methods? Between (
and )
. Why can’t we simply pass lambda arguments between (
and )
like we do with all other arguments? In Scala 2 we have to use {
}
for multiline lambda’s because ;
inference between parentheses doesn’t work. My guess is this whole discussion wouldn’t even exist if a different design had been picked in Scala 2, as suggested in this post:
The only issue I see is that Scala’s “user-defined control structures” become less native looking. But that seems to be almost inevitable with optional braces. All native syntax now defines the start of the “code block” with different keywords such as then
, do
, with
, :
. So perhaps if we want to keep native-looking user-defined control structures just pick one of those keywords and roll with it:
until(foo < bar) do
println(1)
println(2)
test("println should print to the console") do
println(1)
println(2)
// or
until(foo < bar):
println(1)
println(2)
test("println should print to the console"):
println(1)
println(2)
But in that case I think we should emphasize that the accepted way to pass lambdas and multiline arguments is between regular (
and )
, and this is only for usage in DSLs.
Or alternatively don’t pick any code block starting keyword, and let DSL writers get creative with what’s available. E.g. this is already possible:
scala> object Foo { def update(s: String, f: => Unit) = {println("start"); f; println("end")} }; def test = Foo
// defined object Foo
def test: Foo.type
scala> test("println should print to the console") =
| println(1)
| println(2)
|
start
1
2
end
*** As a side note, may I add that using {
}
instead of (
)
for passing arguments is actually a source of confusion for beginners in scala. I’m 99% sure that virtually all suggestions I have seen here will only worsen the initial confusion.
I passionately agree.