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

Named Arguments

Named arguments let you label each input when you call a function, like writing 'size: large, flavor: mint' on an order. You can even give them in any order.

In this page:

  1. Named Arguments
Syntax
scala
function_name(param2 = value2, param1 = value1)

Named Arguments

Calling a function with paramName = value lets you pass arguments in any order and makes the call site self-documenting, especially useful for functions with many parameters of the same type.

Named and positional arguments can be mixed, as long as positional ones come first. This is particularly handy combined with default parameters, letting you skip over earlier defaults.

Note: Named arguments make a call like connect(host = "localhost", port = 8080) far clearer than two unlabeled positional values.

Example: Named Arguments

markup
object Main extends App {
  def describe(name: String, age: Int, city: String): Unit = {
    println(s"$name is $age years old and lives in $city")
  }

  describe(name = "Priya", city = "Mumbai", age = 28)
}
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. Naming a parameter incorrectly, such as describe(nme = "Al"), which fails because the name must match.
  2. Mixing positional arguments after named ones in a way that no longer matches the position, so an argument is passed twice.
  3. Supplying the same parameter both positionally and by name, causing a parameter specified twice error.
🔒

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.