Default parameters in Kotlin allow you to specify default values directly in the function signature, making the code more compact and flexible. This feature enhances readability and eases maintenance, reducing the need to create overloaded methods with varying numbers of arguments.
In Java, for different call variants of a function, it is often necessary to write several overloaded methods. Kotlin has developed a concise way to declare default values, simplifying the API.
Method overloading for different call variants is complex and inconvenient, leading to redundancy in code and potential support errors.
Kotlin allows declaring default parameters directly in the function definition. This is implemented through synthetic companion methods at the JVM bytecode level (when called from Java) or through standard value passing (from Kotlin). Together with named parameters, this makes the function call interface very powerful.
fun greet(name: String = "Guest", greeting: String = "Hello") { println("$greeting, $name!") } greet() // Hello, Guest! greet("Alice") // Hello, Alice! greet(greeting = "Hi") // Hi, Guest! greet("Bob", greeting = "Welcome") // Welcome, Bob!
Can default parameters be used in functions within interfaces?
Yes, but in this case, the default value is only effective when called from Kotlin, and when calling such a method from Java, arguments need to be explicitly specified.
Can a default parameter be specified for the first (non-right) parameters, rather than just the last ones?
Yes, this is possible in Kotlin, especially when using named arguments in the call. However, when using the function from Java, complications may arise since Java does not support named arguments, and default parameters must be on the right.
How does argument order work when mixing positional and named parameters?
In Kotlin, after the first named argument, all subsequent arguments must be named, otherwise a compilation error will occur.
greet("Ivan", greeting = "Zdrastvuyte") // OK greet(greeting = "Zdrastvuyte", "Ivan") // Error: cannot pass positional after named argument
In the logging library, 10 overloaded methods were implemented for different combinations of logging (with Exception, with Tag, without, etc.), making it inconvenient to maintain them.
Pros:
Cons:
A function with default arguments is used:
fun log(msg: String, tag: String = "", throwable: Throwable? = null) { ... }
Pros:
Cons: