Skip to content
← All posts

Kotlin Koans BR · Part 2

Kotlin Koans BR: Named arguments

By 2 min read

🔗 Task

Make the joinOptions() function return the list in JSON format (for example, [a, b, c]) by specifying only two arguments.

You can use the joinToString function available in the stdlib:

fun joinToString(
    separator: String = ", ",
    prefix: String = "",
    postfix: String = "",
    /* ... */
): String

Use case

When you come across Named arguments in Kotlin, you can picture them as putting labels or tags on the values you pass to functions, making everything easier to understand and reducing mistakes.

fun sendEmail(
    from: String,
    to: String,
    subject: String,
) = Unit

Normally, the function would be used like this:

sendEmail(
    "[email protected]",
    "[email protected]",
    "About the Meeting"
)

But when we name the arguments, each value is spelled out clearly:

sendEmail(
    from = "[email protected]",
    to = "[email protected]",
    subject = "About the Meeting"
)

Setting only what you need

Let’s say you only need to set the subject and leave the rest as defaults:

sendEmail(subject = "Meeting Cancelled")

Flexibility in ordering

Want to change the order of the values? No problem, everything is still clear:

sendEmail(
    subject = "Reminder",
    to = "[email protected]",
    from = "[email protected]"
)

Advantages

  • Clarity in function calls: naming arguments removes any doubt about how the values you provide map to the function’s parameters.
  • Flexibility: there’s no need to follow the default parameter order, so you can focus only on the arguments that matter.
  • Error reduction and prevention: by naming arguments, you reduce the chance of accidentally passing the wrong value to a parameter.
  • Implicit documentation: the code becomes self-explanatory, reducing the need for extra comments to explain what each value is for.

Disadvantages

  • Maintaining names: when a parameter name changes in the function definition, every argument that uses that parameter needs to be updated.
  • Verbose calls: in functions with many arguments, naming each one can make the function call long and cluttered.

Analogy

Imagine walking into a library full of books, all with the same cover and no titles on the spine. You know the book you want is in there, but how do you find it among so many identical ones?

This is similar to named arguments in Kotlin. Without clearly identifying the arguments, you can easily get lost, even when you know what you want to do. With named arguments, though, everything becomes clearer, as if each book had its own cover and title.