Default arguments in Kotlin are a convenient feature that allows developers to specify default values for function parameters. This powerful capability enhances code readability and reduces the need for multiple function overloads.
In Kotlin, you can assign default values to function parameters. These values are used when the caller doesn't provide an argument for that specific parameter. This feature is particularly useful when you want to provide a common value for a parameter while still allowing flexibility for different use cases.
To define a default argument, simply assign a value to the parameter in the function declaration:
fun greet(name: String = "Guest") {
println("Hello, $name!")
}
In this example, if no argument is provided for name
, the function will use "Guest" as the default value.
You can call functions with default arguments in two ways:
greet() // Outputs: Hello, Guest!
greet("Alice") // Outputs: Hello, Alice!
Kotlin allows you to define multiple default arguments in a single function:
fun createUser(name: String = "John Doe", age: Int = 30, isAdmin: Boolean = false) {
println("Created user: $name, Age: $age, Admin: $isAdmin")
}
createUser() // Uses all default values
createUser("Alice", 25) // Overrides name and age, uses default for isAdmin
createUser(age = 35, isAdmin = true) // Uses default for name, overrides age and isAdmin
When calling Kotlin functions with default arguments from Java, you need to provide all arguments explicitly. To improve Java interoperability, consider using the @JvmOverloads
annotation, which generates multiple overloaded methods in Java.
Default arguments in Kotlin offer a powerful way to write more flexible and concise code. They work seamlessly with other Kotlin features like named arguments and can significantly improve your codebase's maintainability. As you continue to explore Kotlin, you'll find that default arguments become an essential tool in your programming toolkit.