Home »
Scala
Default parameters in Scala
By IncludeHelp Last updated : October 10, 2024
Default parameters in Scala
A default parameter is a parameter that is declared with a default value in arguments. These default values are used by the functions when no value is passed by the programmer while calling the function.
In its programs, Scala lets its users optionally leave passing values to the parameter. Scala allows you to specify default parameters in a function, and the values for these default parameters can be omitted at the time of the function call. When there is no value passed for an argument in the call of the function, default values are used.
A default parameter is of the same datatype and can have any value within the range. In the case of multiple default parameter, the first one is treated as first and so on.
Syntax
def functionName ( param : Datatype = value )
This syntax defines a default parameters, this function uses its own value that if the function call is without any input parameter. The value is added after the datatype of the parameter and this defines that the values used as default values.
Example of default parameters
object Demo {
def welcome( name: String = "to Include Help" ){
println("Welcome "+ name)
}
def main(args: Array[String]) {
println("This program shows the use of default parameters.");
welcome();
welcome("Shivang")
}
}
Output
This program shows the use of default parameters.
Welcome to Include Help
Welcome Shivang
Code Explanation
The above code shows a basic example of default parameter usage. The code uses a string datatype parameter and has set its default value to the string " to include help" this means if no value is passed as parameter the code will print "Welcome to include help" as shown in output otherwise will print the user name with a welcome message. This types of code are often used by we try to reduce error or NULL value situations.