Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are default parameter values in Scala?

Adnan Abbas

Scala provides the option to define default parameters for functions. This means that the caller would not have to provide those parameters.

Examples

The following program shows a simple example of how we can use default parameters.

def name(first:String  , last:String = "Einstein") = println(first+" "+last)
name("Albert")
name("Max", "Planck")
A simple program demonstrating default parameters in Scala

The parameter last of the name function in the above code is a default parameter. We have defined its default value as "Einstein". Therefore, providing the last argument in the function call in line 2 was optional.

In line 3, the argument "Planck" overrides the default argument "Einstein".

In the example below, both last and first are default parameters. If we specify only one of the parameters, then the first argument will be passed using that parameter, and the second will be taken from the default value, as shown in line 2. We can also omit the first parameter and call the function using the second parameter by naming it, as shown in line 3:

def name(first:String = "Albert"  , last:String = "Einstein") = println(first+" "+last)
name("Paul")
name(last="Markov")

RELATED TAGS

scala

CONTRIBUTOR

Adnan Abbas
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring