Curly Braces and Kotlin

Coming from (old) Java, curly braces usually meant a scoping construct: method scope or just a simple scope for variables.

In Kotlin, However, They have a more meaningful job as a lambda which is usually helpful. But sometimes it is misleading. Consider the following example:

fun sayHello() = { println("Hello!") }

What do you think happens when you call sayHello()?

Just a simple print to the terminal. It’s obvious (at least for me).

Well, think again…

It actually doesn’t do anything except for returning a lambda which will print Hello on invocation.

Just had a similar case in my tests last week:

See if you can spot that error as well. Tests were not running the assertions at all.

And here is the fix:

Using return values and avoiding side effects usually helps to prevent such cases. But is also worth to be just aware of that pitfall.

That’s it for now.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store