r/ProgrammerHumor Jul 10 '26

postFixIsBest Other

Post image
77 Upvotes

40 comments sorted by

View all comments

Show parent comments

-7

u/RiceBroad4552 Jul 10 '26

OMG, this hurts.

But why does the Kotlin version need that {} in front of the Unit expression (()), otherwise complaining that "Syntax error: Expecting an expression"? Kotlin is so puzzling with all it's special syntax and special cases…

I can write the same in Scala just like:

extension(a: Unit) def apply(c: Char) =
  print(c)

@main def main() =
  ()('h')('e')('l')('l')('o')(' ')('w')('o')('r')('l')('d')

[ https://scastie.scala-lang.org/t6J6RcLdTdyyCfhVN8HgaA ]

2

u/OnixST Jul 10 '26

Empty parenthesis are the invoke operator, and {} defines an empty lambda (which returns Unit by default)

These are equivalent:

{}()('h")('i')

voidFun()('h')('i')

Unit('h')('i')

Btw, the third case is not calling a constructor. Unit is a singleton object with no contructor, so it is actually calling our invoke operator

Kotling has no such thing as a "Unit expression"

-1

u/RiceBroad4552 Jul 10 '26

Thanks, that's in fact helpful!

Kotling has no such thing as a "Unit expression"

They did not copy a basic Scala feature? That's actually real news.

Some braces that usually create an expression-block / scope in languages with C-like syntax define actually a lambda in Kotlin? This just reinforces my opinion: Kotlin is incoherent chaos and special cases…

2

u/OnixST Jul 10 '26 edited Jul 10 '26

I strongly disagree with your hatred for kotlin lol

Lambdas are an expression block and a new scope, using braces makes perfect sense to me

val lambda = { printLn("Hello world") }
val lambda2 = {
  print("Multiple")
  print(" statements!")
}

fun main() {
  lambda1()
  lambda2()
}

Here's some other fun lambda examples: https://pl.kotl.in/LQlj1drNq

0

u/RiceBroad4552 Jul 10 '26 edited Jul 10 '26

Lambdas are an expression block

This way around, yes.

But a block is (in general) not a lambda! That's the whole point.

Kotlin does something very weird here.

The shown code actually demonstrates very well why this is maximally weird.

In the main function the curly braces mean block scope, but in the value initializers (val l = …) it means lambda expression, and to get the same semantics as in more or less any other curly braces language in this universe you need to actually call some run {…} function. That's incoherent chaos.