Curly brackets or normal brackets in Kotlin ?

Paul Newport
2 min readJan 21, 2024

--

In the early days of being a Java developer learning Kotlin, I often got really confused as to whether I should be using normal brackets () or curly brackets/braces {} when coding. It seemed a random cryptic convention, but once I understood what was going on, the mystery was solved.

As an example, let’s look at some Java code, and the Kotlin equivalent.

Here’s a simple forEach loop, that iterates through a collection, and prints out the value of each item in the loop. forEach is just a function, so it takes parameters inside normal brackets. The parameter is just a lambda, so that is provided as the parameter (“string”) and the lines of code to execute inside braces, like so:

var addresses = List.of("One", "Two", "Three");
addresses.forEach(string -> {
System.out.println(string);
}

Let’s look at how we can achieve the same code in Kotlin, firstly in a Java like manner, and secondly in a more concise format.

val addresses = listOf("One", "Two", "Three")
addresses.forEach({
string ->
println(string)
})

The code is pretty similar. However you are far more likely to see code done like this instead:

val addresses = listOf("One", "Two", "Three")
addresses.forEach { string ->
println(string)
}

What’s going on ? Where have the normal brackets gone ? Why is the function call using braces instead? Aren’t functions were supposed to pass parameters within normal brackets ?

Kotlin has a handy feature, that says that if the last parameter of a function is a function, then it can be passed outside the brackets, like so :

val addresses = listOf("One", "Two", "Three")
addresses.forEach() { string ->
println(string)
}

In these type of situations, it’s often the case that the function only has a single parameter, the lambda, in which case the normal brackets are redundant, and can be deleted. This style of coding is used all the time in Kotlin, and is the basis of Kotlin DSLs.

Kotlin has another feature that is very often used in conjunction with the above rule: if the lambda only has one parameter, you don’t need to define it, and can instead use a parameter called “it” that is provided automatically.

This results in even more compact code:

addresses.forEach {
println(it)
}

In summary, both Java and Kotlin pass parameters to methods/functions via normal brackets, but in Kotlin, if the last parameter is a function, then it can be passed outside the brackets, and if there is only one parameter, the brackets can be removed altogether.

--

--

Paul Newport

Software developer since the stone age. Kotlin and Spring fan.