ProgrammingAndroid Developer

How do default arguments and named parameters work in Kotlin? Discuss the differences from Java, nuances of argument passing, compilation with overload methods, order of named and positional parameters. Provide an example.

Pass interviews with Hintsage AI assistant

Answer.

Kotlin supports default arguments and named parameters, which provides greater flexibility compared to Java.

Key points:

  • In Kotlin, function parameters can have default values:
    fun greet(name: String = "User", greeting: String = "Hello") { println("$greeting, $name!") }
  • You can call a function by specifying only the required parameters — the others will be filled by default.
  • Named parameters allow you to explicitly specify the argument name — especially convenient when a function has many parameters:
    greet(greeting = "Hi") // -> Hi, User!
  • You can combine regular (positional) and named parameters, as long as named parameters are not used in the middle of the call.
  • Unlike Java (where overloads are created for each combination), Kotlin compiles default arguments into overload methods only for interop with Java, and this is not visible from within Kotlin.

Nuances:

  • After using a named argument, the following arguments must also be named.
  • To use functions with default parameters from Java, the @JvmOverloads annotation may be required.

Trick question.

Can you mix positional and named arguments in any order when calling a function in Kotlin?

Correct answer: No, after you specify at least one named argument, all subsequent arguments must also be named. Violating this will cause a compilation error.

// Incorrect greet(greeting = "Hi", "Ivan") // Error! // Correct greet("Ivan", greeting = "Hi") greet(name = "Ivan", greeting = "Hi")

Examples of real errors due to ignorance of the nuances of the topic.


Story

The team integrated a Kotlin module with a legacy Java project and forgot to add the @JvmOverloads annotation for the function with default parameters. As a result, the Java code did not see the necessary overload methods — runtime errors occurred during calls.


Story

During refactoring using named parameters, a developer accidentally switched the arguments — subsequent renaming of parameters went unnoticed (the typing was not violated, but the call semantics changed!). This led to strange bugs in the UI logic, discovered later.


Story

One of the developers, in an attempt to improve readability, mixed positional and named arguments in the middle of the call. The code did not compile, but the team struggled to understand what the problem was — as they often encountered this in other languages and expected similar behavior from Kotlin.