Named and optional parameters
suggest changeKotlin allows functions and constructors to define default parameter values (optional parameters) and callers to specify argument values by parameter name (named arguments). This significantly reduces boilerplate by eliminating the need for method overloading cascades and builder patterns common in other JVM languages.
Default Parameters (Optional Parameters)
Parameters can specify default values using the = syntax after the parameter type. If an argument is omitted at the call site, the default value is used.
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!"): String {
return "$greeting, $name$punctuation"
}
fun main() {
println(greet("Alice")) // Output: Hello, Alice!
println(greet("Bob", "Good morning")) // Output: Good morning, Bob!
println(greet("Charlie", "Hi", "!!")) // Output: Hi, Charlie!!
}
Default argument expressions are evaluated lazily at the call site when the function is invoked, meaning they can reference preceding parameters or call dynamic functions:
fun calculatePrice(basePrice: Double, taxRate: Double = 0.08, discount: Double = 0.0): Double {
return (basePrice * (1 + taxRate)) - discount
}
fun log(message: String, timestamp: Long = System.currentTimeMillis()) {
println("[$timestamp] $message")
}
Named Arguments
When invoking a function, you can label one or more arguments by their parameter names. This eliminates ambiguity when functions accept multiple parameters of the same type.
fun configureWindow(
title: String,
width: Int = 800,
height: Int = 600,
resizable: Boolean = true,
fullscreen: Boolean = false
) {
println("Window '$title': ${width}x$height, resizable=$resizable, fullscreen=$fullscreen")
}
fun main() {
// Reordering arguments using names
configureWindow(
title = "Dashboard",
fullscreen = true,
height = 1080,
width = 1920
)
// Selectively overriding only specific default parameters
configureWindow(
title = "Settings Dialog",
resizable = false
)
}
Mixing Positional and Named Arguments
Positional arguments can be mixed with named arguments, as long as all positional arguments appear before the first named argument (or match their natural parameter order):
// "Main App" is positional (first parameter `title`), width & height are named
configureWindow("Main App", width = 1024, height = 768)
Default Parameters and Inheritance
When overriding a method that has default parameter values in a base class or interface, the override must omit default values. The default values are inherited from the base declaration:
open class NotificationService {
open fun send(message: String, priority: String = "NORMAL") {
println("Sending [$priority]: $message")
}
}
class EmailService : NotificationService() {
// Priority parameter CANNOT redeclare '= "NORMAL"'
override fun send(message: String, priority: String) {
println("Email [$priority]: $message")
}
}
fun main() {
val service = EmailService()
service.send("System maintenance notice") // Uses base default: "NORMAL"
}
Combining with Lambdas and Trailing Lambdas
When the last parameter is a lambda with a default implementation, callers can use Kotlin's trailing lambda syntax or fall back to the default:
fun executeTask(
name: String,
timeoutMs: Long = 5000,
onSuccess: (String) -> Unit = { println("Task $it completed.") }
) {
// Simulating task execution
onSuccess(name)
}
fun main() {
// Using default lambda
executeTask("BackupJob")
// Overriding with trailing lambda
executeTask("ReportJob", timeoutMs = 2000) { job ->
println("Custom success handler for $job")
}
}
Java Interoperability: @JvmOverloads
By default, Kotlin generates only a single JVM method containing all parameters, plus a synthetic helper method handling default value bitmasks. Java code calling this Kotlin function would normally be forced to provide all arguments.
To generate standard overloaded methods in Java bytecode, annotate the function or constructor with @JvmOverloads:
class UserAccount @JvmOverloads constructor(
val username: String,
val email: String,
val isActive: Boolean = true,
val role: String = "USER"
)
@JvmOverloads
fun createButton(label: String, width: Int = 100, height: Int = 40): String {
return "Button($label, $width, $height)"
}
From Java, @JvmOverloads generates:
createButton(String label)createButton(String label, int width)createButton(String label, int width, int height)
Best Practices
- Avoid Boolean Flag Traps: When calling methods with multiple boolean flags (e.g.
save(true, false, true)), always use named arguments (save(flush = true, async = false, validate = true)) for clarity. - Place Mandatory Parameters First: Declare parameters without defaults before parameters with defaults, allowing callers to omit names for positional mandatory parameters.
- Use Named Arguments in Data Classes: Calling
.copy()on data classes with named arguments makes state transitions clear and resilient to future property additions:data class User(val id: Long, val name: String, val active: Boolean) val updated = user.copy(active = false) - Be Careful with Public ABI Compatibility: Adding a new parameter with a default value maintains source compatibility in Kotlin, but alters the JVM bytecode signature. Always test binary compatibility in shared libraries.