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:
Syntax
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
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)
}
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
- Naming a parameter incorrectly, such as
describe(nme = "Al"), which fails because the name must match. - Mixing positional arguments after named ones in a way that no longer matches the position, so an argument is passed twice.
- Supplying the same parameter both positionally and by name, causing a
parameter specified twiceerror.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: