0
0
Kotlinprogramming~15 mins

Parameters with default values in Kotlin - Deep Dive

Choose your learning style9 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.