Curly Braces and Kotlin

osha1
1 min readJan 17, 2019

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.

--

--