Skip to main content

Set Default Values for Function Parameters in Kotlin

When you define a function, you can specify default values for its parameters. This way, if the caller of the function does not provide a value for that parameter, the default value will be used. This is how you can set default values for function parameters in Kotlin:

fun myFunction(param1: String = "defaultValue1", param2: Boolean = false) { 
    //do something here
}

In the example above, we have two parameters, param1, and param2, both with default values. If the caller of the function does not provide a value for either of these parameters, the respective default value will be used.

You can also mix and match parameters with and without default values. For example, you can have a function with two parameters, one with a default value and one without:

fun myFunction(param1: String, param2: String = "defaultValue") {
    // function body goes here
}

In this case, if the caller of the function does not provide a value for param1 , an error will occur. However, if the caller does not provide a value for param2 , the default value will be used.

Keep in mind that you can only set default values for parameters that are listed after all the parameters without default values. For example, the following is not valid Kotlin code:

//this throw an error
fun myFunction(param1: String = "defaultValue", param2: String) { 
    // function body goes here 
}

If you try to compile the code above, you will get an error.

By continuing to use the site, you agree to the use of cookies.