← Back to Scala Course | Chapter 5: Functions | Lesson 3 of 7

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:

  1. Default Parameters
Syntax
scala
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

markup
object Main extends App {
  def greet(name: String, greeting: String = "Hello"): Unit = {
    println(s"$greeting, $name!")
  }

  greet("Alice")
  greet("Bob", "Welcome")
}
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
  1. Placing a default parameter before required ones and calling with only positional arguments, which supplies the wrong values.
  2. Passing arguments in the wrong order, such as greet("Hi", "Alice"), when name comes first and greeting has the default.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.