Bird
Raised Fist0
Kotlinprogramming~15 mins

Parameters with default values in Kotlin - Deep Dive

Choose your learning style10 modes available
Overview - Parameters with default values
What is it?
Parameters with default values allow you to give a function's input a preset value. This means if you don't provide that input when calling the function, it uses the default automatically. It helps make functions easier to use and reduces the need for multiple versions of the same function. You can think of it as having a backup value ready to go.
Why it matters
Without default values, you would have to write many similar functions just to handle different input cases. This makes code longer, harder to read, and more error-prone. Default parameters simplify function calls and improve code clarity, saving time and reducing bugs. They let you write flexible functions that adapt to different needs without extra work.
Where it fits
Before learning default parameters, you should understand basic functions and how to pass arguments in Kotlin. After mastering this, you can explore named arguments and function overloading, which also help with flexible function calls.
Mental Model
Core Idea
A function parameter with a default value acts like a preset option that the function uses when no specific input is given.
Think of it like...
Imagine ordering a coffee where the barista asks if you want milk. If you don't say anything, they automatically add regular milk. The default milk is like the default parameter in a function.
Function call with default parameters:

┌───────────────┐
│ Function foo  │
│ Parameters:   │
│  x: Int = 10  │
│  y: String    │
└──────┬────────┘
       │
       │ Call foo(5, "Hi")  → uses x=5, y="Hi"
       │ Call foo(y = "Hi")  → uses x=10 (default), y="Hi"
       ▼
Build-Up - 7 Steps
1
FoundationUnderstanding basic function parameters
🤔
Concept: Learn how to define and call functions with parameters in Kotlin.
In Kotlin, functions can take inputs called parameters. For example: fun greet(name: String) { println("Hello, $name!") } You call it by passing a value: greet("Alice") This prints: Hello, Alice!
Result
The function prints a greeting using the provided name.
Knowing how to pass parameters is the foundation for understanding how default values can simplify function calls.
2
FoundationCalling functions with multiple parameters
🤔
Concept: Learn how to define functions with more than one parameter and call them.
Functions can have many parameters: fun describe(age: Int, city: String) { println("Age: $age, City: $city") } Call it with: describe(25, "Paris") This prints: Age: 25, City: Paris
Result
The function prints the age and city passed as arguments.
Understanding multiple parameters prepares you to see how default values can reduce the need to specify all arguments every time.
3
IntermediateIntroducing default parameter values
🤔Before reading on: do you think Kotlin requires all parameters to be passed every time? Commit to yes or no.
Concept: Kotlin lets you assign default values to parameters, so you can skip them when calling the function.
You can write: fun greet(name: String = "Guest") { println("Hello, $name!") } Calling greet() prints: Hello, Guest! Calling greet("Alice") prints: Hello, Alice!
Result
The function uses the default name "Guest" if no argument is given.
Understanding default values lets you write simpler calls and avoid unnecessary repetition.
4
IntermediateCombining default and non-default parameters
🤔Before reading on: if a function has some parameters with defaults and some without, do you think you can skip only the default ones when calling it? Commit to yes or no.
Concept: Functions can mix parameters with and without default values, but you must provide values for those without defaults.
Example: fun describe(age: Int, city: String = "Unknown") { println("Age: $age, City: $city") } Call describe(30) prints: Age: 30, City: Unknown Call describe(30, "Berlin") prints: Age: 30, City: Berlin You cannot skip 'age' because it has no default.
Result
You must provide arguments for parameters without defaults; others can use defaults.
Knowing which parameters require values helps avoid errors and write flexible functions.
5
IntermediateUsing named arguments with default parameters
🤔Before reading on: do you think named arguments let you skip parameters in any order? Commit to yes or no.
Concept: Named arguments let you specify only some parameters by name, skipping others that have defaults.
Example: fun bookTicket(seat: String = "A1", price: Int = 100) { println("Seat: $seat, Price: $price") } Call bookTicket(price = 150) prints: Seat: A1, Price: 150 You can skip 'seat' by naming 'price' explicitly.
Result
Named arguments combined with defaults give flexible function calls.
Understanding named arguments unlocks powerful ways to call functions clearly and selectively.
6
AdvancedDefault parameters vs function overloading
🤔Before reading on: do you think default parameters completely replace function overloading? Commit to yes or no.
Concept: Default parameters reduce the need for multiple overloaded functions but don't replace all use cases.
Instead of: fun printMessage() { printMessage("Hello") } fun printMessage(msg: String) { println(msg) } You can write: fun printMessage(msg: String = "Hello") { println(msg) } But overloading is still useful for different parameter types or counts.
Result
Default parameters simplify code but don't cover all overloading scenarios.
Knowing when to use defaults or overloads helps write clearer, maintainable code.
7
ExpertHow default parameters affect bytecode and performance
🤔Before reading on: do you think default parameters add no extra code or runtime cost? Commit to yes or no.
Concept: Kotlin compiles default parameters by generating extra methods and synthetic code, which can affect bytecode size and interoperability.
Kotlin creates a special method with all parameters and a mask to track which defaults to use. This adds some overhead compared to plain functions. Example: For fun foo(a: Int = 1, b: Int = 2), Kotlin generates foo with parameters and a bitmask to decide which defaults to apply. This can affect Java interoperability and reflection.
Result
Default parameters add hidden code that manages which values to use at runtime.
Understanding the compiled form helps avoid surprises in performance and cross-language use.
Under the Hood
When you define a function with default parameters, Kotlin generates a single method with all parameters plus an extra integer bitmask and a dummy parameter. The bitmask indicates which parameters were omitted and should use their default values. At runtime, the method checks the bitmask to decide whether to use the passed argument or the default. This mechanism allows Kotlin to keep a single function instead of multiple overloads.
Why designed this way?
This design balances code size and flexibility. Instead of generating many overloaded functions for every combination of parameters, Kotlin uses a bitmask to handle defaults efficiently. It also preserves backward compatibility and interoperability with Java, which does not support default parameters natively.
┌───────────────────────────────┐
│ Kotlin function with defaults  │
│ Parameters: a, b (with defaults)│
└───────────────┬───────────────┘
                │
                ▼
┌─────────────────────────────────────────────┐
│ Generated method with parameters:           │
│ a, b, bitmask, dummy                        │
│                                             │
│ if (bitmask & 0x1 != 0) use default for a   │
│ if (bitmask & 0x2 != 0) use default for b   │
└─────────────────────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think all parameters with defaults can be skipped in any order when calling a function? Commit to yes or no.
Common Belief:You can skip any default parameter in any order without naming them.
Tap to reveal reality
Reality:You must either provide arguments in order or use named arguments to skip parameters out of order.
Why it matters:Ignoring this causes compilation errors or unexpected argument assignments.
Quick: Do you think default parameters increase runtime overhead significantly? Commit to yes or no.
Common Belief:Default parameters always slow down function calls noticeably.
Tap to reveal reality
Reality:The overhead is minimal and usually negligible, but there is some extra bytecode generated.
Why it matters:Overestimating overhead might lead to premature optimization or avoiding useful features.
Quick: Do you think default parameters work the same way in Java as in Kotlin? Commit to yes or no.
Common Belief:Java supports default parameters just like Kotlin.
Tap to reveal reality
Reality:Java does not support default parameters; Kotlin uses generated methods and bitmasks to simulate them.
Why it matters:Assuming Java supports defaults can cause interoperability bugs and confusion.
Quick: Do you think function overloading is unnecessary if you use default parameters? Commit to yes or no.
Common Belief:Default parameters completely replace the need for function overloading.
Tap to reveal reality
Reality:Overloading is still needed for different parameter types or when default values are not enough.
Why it matters:Misusing defaults instead of overloading can lead to unclear or incorrect code.
Expert Zone
1
Default parameters generate synthetic methods with bitmasks, which can complicate reflection and debugging.
2
Using default parameters in public APIs requires careful consideration for Java interoperability, as Java callers must provide all arguments.
3
Combining default parameters with inline functions can affect inlining behavior and bytecode size.
When NOT to use
Avoid default parameters when you need to support Java callers directly or when parameter combinations require very different logic better handled by overloading or separate functions.
Production Patterns
In production Kotlin code, default parameters are commonly used to simplify APIs, reduce overloads, and provide backward compatibility. Libraries often use them to add new parameters without breaking existing calls.
Connections
Function overloading
Alternative approach to achieve flexible function calls
Understanding default parameters helps you decide when to use overloading or defaults for cleaner code.
Named arguments
Works together with default parameters to allow skipping and reordering arguments
Knowing named arguments unlocks the full power of default parameters for readable and flexible calls.
User interface design
Both use defaults to simplify choices and reduce user effort
Recognizing default parameters as a way to provide sensible defaults mirrors how UI design reduces decision fatigue.
Common Pitfalls
#1Skipping a non-default parameter when calling a function
Wrong approach:fun greet(name: String = "Guest", age: Int) { println("$name is $age years old") } greet()
Correct approach:fun greet(name: String = "Guest", age: Int) { println("$name is $age years old") } greet(age = 30)
Root cause:Parameters without defaults must always be provided; forgetting this causes errors.
#2Calling a function with default parameters without using named arguments when skipping middle parameters
Wrong approach:fun book(seat: String = "A1", price: Int = 100, vip: Boolean = false) { println("Seat: $seat, Price: $price, VIP: $vip") } book(, 150)
Correct approach:book(price = 150)
Root cause:Kotlin requires named arguments to skip parameters in the middle; positional arguments must be in order.
#3Assuming default parameters work the same in Java when calling Kotlin functions
Wrong approach:// Java code MyKotlinClass.foo(); // expects all parameters, no defaults
Correct approach:// Java code MyKotlinClass.foo(10, "text"); // must provide all arguments
Root cause:Java does not support Kotlin's default parameters; callers must provide all arguments.
Key Takeaways
Default parameters let you assign preset values to function inputs, making calls simpler and clearer.
You must provide values for parameters without defaults; only those with defaults can be skipped or omitted.
Named arguments work hand-in-hand with default parameters to allow skipping and reordering arguments safely.
Default parameters reduce the need for many overloaded functions but do not replace overloading entirely.
Under the hood, Kotlin uses bitmasks and synthetic methods to implement default parameters, affecting bytecode and interoperability.

Practice

(1/5)
1. What happens when you call a Kotlin function with a parameter that has a default value but you don't provide an argument for it?
fun greet(name: String = "Guest") { println("Hello, $name!") }
easy
A. The function uses the default value for the missing parameter.
B. The function throws an error because the argument is missing.
C. The function ignores the parameter and prints nothing.
D. The function requires you to always provide the argument.

Solution

  1. Step 1: Understand default parameter behavior

    In Kotlin, if a parameter has a default value, the function can be called without providing that argument.
  2. Step 2: Apply to the example function

    Calling greet() will use the default value "Guest" for name, printing "Hello, Guest!".
  3. Final Answer:

    The function uses the default value for the missing parameter. -> Option A
  4. Quick Check:

    Default parameter means optional argument [OK]
Hint: If argument missing, default value is used automatically [OK]
Common Mistakes:
  • Thinking missing argument causes error
  • Assuming function ignores missing parameters
  • Believing all parameters must be provided
2. Which of the following is the correct way to declare a Kotlin function with a default parameter value?
easy
A. fun add(a: Int, b: Int default 5) { return a + b }
B. fun add(a: Int = 5, b: Int) { return a + b }
C. fun add(a: Int, b: Int) = a + b = 5
D. fun add(a: Int, b: Int = 5) { return a + b }

Solution

  1. Step 1: Check Kotlin syntax for default parameters

    In Kotlin, default values are assigned using = after the parameter type, like b: Int = 5.
  2. Step 2: Validate each option

    fun add(a: Int, b: Int = 5) { return a + b } correctly uses b: 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.
  3. Final Answer:

    fun add(a: Int, b: Int = 5) { return a + b } -> Option D
  4. Quick Check:

    Default value syntax = parameter: Type = value [OK]
Hint: Use '=' after type to set default value [OK]
Common Mistakes:
  • Placing default value before type
  • Using 'default' keyword instead of '='
  • Assigning default outside parameter list
3. What is the output of the following Kotlin code?
fun multiply(x: Int, y: Int = 2) = x * y

println(multiply(4))
medium
A. 8
B. 4
C. Error: Missing argument for y
D. 2

Solution

  1. Step 1: Identify default parameter usage

    The function multiply has a default value of 2 for y. Calling multiply(4) means x=4 and y=2.
  2. Step 2: Calculate the result

    Multiply 4 by 2 to get 8.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Default y=2 used, 4*2=8 [OK]
Hint: If argument missing, default value is used [OK]
Common Mistakes:
  • Expecting error for missing argument
  • Using only first argument as output
  • Confusing default value with zero
4. Identify the error in this Kotlin function declaration:
fun greet(name: String = "User", age: Int) {
    println("Hello, $name! You are $age years old.")
}
medium
A. Cannot use default values with String parameters.
B. Default parameter must be last or followed by named arguments.
C. Function must return a value if default parameters are used.
D. No error, function is correct.

Solution

  1. 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.
  2. Step 2: Analyze given function

    Here, name has a default but comes before age which has no default. This causes a problem when calling without named arguments.
  3. Final Answer:

    Default parameter must be last or followed by named arguments. -> Option B
  4. Quick Check:

    Default parameters after non-default or use named args [OK]
Hint: Place default parameters after non-default ones [OK]
Common Mistakes:
  • Putting default parameters before required ones
  • Assuming all parameters can have defaults anywhere
  • Ignoring named argument calls
5. You want to write a Kotlin function 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?
hard
A. fun formatMessage(prefix: String = "Info:", message: String) = "$prefix $message"
B. fun formatMessage(message: String, prefix: String) = "$prefix $message"
C. fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message"
D. fun formatMessage(message: String = "Info:", prefix: String) = "$prefix $message"

Solution

  1. Step 1: Define function with default parameter last

    The optional parameter prefix with default value should come after the required message parameter.
  2. Step 2: Check each option

    fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" correctly places prefix last 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.
  3. Final Answer:

    fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" -> Option C
  4. Quick Check:

    Default last parameter enables optional argument [OK]
Hint: Put default parameters after required ones for easy calls [OK]
Common Mistakes:
  • Placing default parameter before required parameter
  • Not providing default value for optional parameter
  • Confusing parameter order causing call errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard