Default Values
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 59 of 93.
Sometimes you want a function parameter to have a fallback value when the caller doesn't provide one. Kotlin lets you assign default values directly in the parameter definition.
fun greet(name: String = "Guest") {
println("Hello, $name!")
}
fun main() {
greet("Alice")
greet()
}
// Output:
// Hello, Alice!
// Hello, Guest!When calling greet() without an argument, Kotlin uses the default value "Guest". This makes functions more flexible - callers can customize behavior when needed or rely on sensible defaults.
You can mix parameters with and without defaults. Parameters with defaults typically come last:
fun createUser(name: String, role: String = "member"): String {
return "$name ($role)"
}
fun main() {
println(createUser("Alice", "admin"))
println(createUser("Bob"))
}
// Output:
// Alice (admin)
// Bob (member)Named arguments become especially useful with default values. They let you skip parameters while providing others:
fun format(text: String, uppercase: Boolean = false, prefix: String = "") {
val result = if (uppercase) text.uppercase() else text
println("$prefix$result")
}
fun main() {
format("hello", prefix = "-> ")
}
// Output: -> helloChallenge
MediumImplement buildGreeting(name: String, greeting: String = "Hello"): String. Return a greeting in the form greeting, name!. The supplied test driver calls your function twice: once with just the name, and once with a name and an explicit greeting. Do not write main or print inside the function. The missing greeting must use the default "Hello".
Try it yourself
fun buildGreeting(name: String, greeting: String): String {
// Add the default value to the parameter and return the greeting.
TODO("Build the greeting")
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground