How to Use Default Parameter in Kotlin: Simple Guide
In Kotlin, you can define a function parameter with a
default value by assigning it in the function declaration like fun greet(name: String = "Guest"). This allows calling the function without passing that argument, and the default will be used automatically.Syntax
To use a default parameter in Kotlin, assign a value to the parameter in the function definition. This value is used if no argument is provided when calling the function.
- Parameter name: The name of the argument.
- Type: The data type of the parameter.
- Default value: The value assigned with
=that is used if no argument is passed.
kotlin
fun functionName(parameterName: Type = defaultValue) {
// function body
}Example
This example shows a function greet with a default parameter name. If no name is given, it uses "Guest".
kotlin
fun greet(name: String = "Guest") { println("Hello, $name!") } fun main() { greet("Alice") // prints: Hello, Alice! greet() // prints: Hello, Guest! }
Output
Hello, Alice!
Hello, Guest!
Common Pitfalls
Common mistakes include:
- Not providing default values for all optional parameters when calling with named arguments.
- Placing parameters with default values before those without, which can cause confusion.
- Overloading functions unnecessarily instead of using default parameters.
Always put parameters with default values after required parameters to avoid ambiguity.
kotlin
/* Wrong: default parameter before non-default */ fun example(a: Int = 5, b: Int) { } /* Right: default parameter after non-default */ fun example(b: Int, a: Int = 5) { }
Quick Reference
Tips for using default parameters in Kotlin:
- Define default values directly in the function signature.
- Call functions without arguments to use defaults.
- Use named arguments to skip some parameters.
- Place parameters with defaults at the end.
Key Takeaways
Default parameters let you assign fallback values in function definitions.
You can call functions without arguments to use default values automatically.
Always place parameters with default values after required ones.
Use named arguments to specify only some parameters when calling functions.
Default parameters reduce the need for multiple overloaded functions.