0
0
Kotlinprogramming~5 mins

Parameters with default values in Kotlin

Choose your learning style9 modes available
Introduction

Parameters with default values let you give a starting value to a function's input. This way, you can call the function without always giving all inputs.

When you want a function to work even if some inputs are missing.
When you want to avoid writing many function versions for different input counts.
When you want to keep your code simple and clear by using common default settings.
When you want to make your functions flexible for different situations.
Syntax
Kotlin
fun functionName(param1: Type = defaultValue, param2: Type = defaultValue) {
    // function body
}

Default values are set using the equals sign (=) after the parameter type.

If you skip a parameter with a default value when calling the function, Kotlin uses the default.

Examples
This function says hello. If you don't give a name, it uses "Friend".
Kotlin
fun greet(name: String = "Friend") {
    println("Hello, $name!")
}
This function multiplies two numbers. If you skip the second number, it multiplies by 2.
Kotlin
fun multiply(a: Int, b: Int = 2): Int {
    return a * b
}
This function prints name and age. Both have default values.
Kotlin
fun printInfo(name: String = "Unknown", age: Int = 0) {
    println("Name: $name, Age: $age")
}
Sample Program

This program shows how the greet function works with and without a parameter.

Kotlin
fun greet(name: String = "Friend") {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")  // Uses given name
    greet()          // Uses default name
}
OutputSuccess
Important Notes

You can mix parameters with and without default values, but parameters without defaults must come first.

Using default values helps avoid writing many overloaded functions.

Summary

Default parameter values let functions have optional inputs.

If you skip a parameter, Kotlin uses its default value.

This makes your code simpler and easier to use.