What if you could write one function that works perfectly in many situations without extra hassle?
Why Parameters with default values in Kotlin? - Purpose & Use Cases
Imagine you have a function that greets users. Sometimes you want to greet by name, other times just a simple hello. Without default values, you must write many versions of the same function or always provide all details.
Writing many function versions is tiring and error-prone. You might forget to update all versions when changing logic. Also, calling functions with many parameters every time is slow and confusing.
Parameters with default values let you write one function that works in many ways. You can skip parameters you don't want to change, making your code cleaner and easier to read.
fun greet(name: String) { println("Hello, $name!") }
fun greet() { println("Hello!") }fun greet(name: String = "there") { println("Hello, $name!") }
You can write simpler, flexible functions that adapt to different needs without extra code.
When making a messaging app, you can create a sendMessage function with default parameters for things like font size or color, so users get a nice message even if they don't customize every detail.
Default parameters reduce repetitive code.
They make functions easier to call and maintain.
They help your code stay clean and flexible.
Practice
fun greet(name: String = "Guest") { println("Hello, $name!") }Solution
Step 1: Understand default parameter behavior
In Kotlin, if a parameter has a default value, the function can be called without providing that argument.Step 2: Apply to the example function
Callinggreet()will use the default value "Guest" forname, printing "Hello, Guest!".Final Answer:
The function uses the default value for the missing parameter. -> Option AQuick Check:
Default parameter means optional argument [OK]
- Thinking missing argument causes error
- Assuming function ignores missing parameters
- Believing all parameters must be provided
Solution
Step 1: Check Kotlin syntax for default parameters
In Kotlin, default values are assigned using=after the parameter type, likeb: Int = 5.Step 2: Validate each option
fun add(a: Int, b: Int = 5) { return a + b } correctly usesb: Int = 5. fun add(a: Int = 5, b: Int) { return a + b } places default before non-default parameter, which is allowed but can cause ambiguity if called without named arguments. Options A and C have invalid syntax.Final Answer:
fun add(a: Int, b: Int = 5) { return a + b } -> Option DQuick Check:
Default value syntax = parameter: Type = value [OK]
- Placing default value before type
- Using 'default' keyword instead of '='
- Assigning default outside parameter list
fun multiply(x: Int, y: Int = 2) = x * y println(multiply(4))
Solution
Step 1: Identify default parameter usage
The functionmultiplyhas a default value of 2 fory. Callingmultiply(4)meansx=4andy=2.Step 2: Calculate the result
Multiply 4 by 2 to get 8.Final Answer:
8 -> Option AQuick Check:
Default y=2 used, 4*2=8 [OK]
- Expecting error for missing argument
- Using only first argument as output
- Confusing default value with zero
fun greet(name: String = "User", age: Int) {
println("Hello, $name! You are $age years old.")
}Solution
Step 1: Check parameter order rules
In Kotlin, parameters with default values should be placed after parameters without default values, or you must use named arguments when calling.Step 2: Analyze given function
Here,namehas a default but comes beforeagewhich has no default. This causes a problem when calling without named arguments.Final Answer:
Default parameter must be last or followed by named arguments. -> Option BQuick Check:
Default parameters after non-default or use named args [OK]
- Putting default parameters before required ones
- Assuming all parameters can have defaults anywhere
- Ignoring named argument calls
formatMessage that takes a message and an optional prefix with default value "Info:". It should return the combined string. Which function correctly implements this and allows calling with or without the prefix?Solution
Step 1: Define function with default parameter last
The optional parameterprefixwith default value should come after the requiredmessageparameter.Step 2: Check each option
fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" correctly placesprefixlast with default. fun formatMessage(prefix: String = "Info:", message: String) = "$prefix $message" places default before required, which can cause call issues. Options C and D lack default for prefix or have wrong order.Final Answer:
fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" -> Option CQuick Check:
Default last parameter enables optional argument [OK]
- Placing default parameter before required parameter
- Not providing default value for optional parameter
- Confusing parameter order causing call errors
Ready to prove it?
Pass the test and this pattern moves unknown
