Default Parameters
A default parameter has a ready-made value used when you do not give one, like a burger that comes with cheese unless you say no. It lets callers skip inputs.
In this page:
Syntax
def function_name(param1: Type, param2: Type = default_value): ReturnType = {
// body
}
Default Parameters
A parameter can specify a default value in its declaration, def greet(name: String, greeting: String = "Hello"), making it optional at the call site.
If the caller doesn't supply it, the default is used. Default parameters are commonly combined with named arguments to skip earlier defaults while still setting a later one.
Note:
Default parameters pair naturally with named arguments -- you can override just one default deep in the parameter list without repeating the others.
Example: Default Parameters
object Main extends App {
def greet(name: String, greeting: String = "Hello"): Unit = {
println(s"$greeting, $name!")
}
greet("Alice")
greet("Bob", "Welcome")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Placing a default parameter before required ones and calling with only positional arguments, which supplies the wrong values.
- Passing arguments in the wrong order, such as
greet("Hi", "Alice"), whennamecomes first andgreetinghas the default. - Expecting overloaded methods to all accept defaults, when only one overloaded alternative may define default arguments.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: