5.3. Setting Default Values for Method Parameters
Problem
You want to set default values for method parameters so the method can optionally be called without those parameters having to be assigned.
Solution
Specify the default value for parameters in the method signature.
In the following code, the timeout
field is assigned a default value of 5000
, and the protocol
field is given a default value of
"http"
:
class
Connection
{
def
makeConnection
(
timeout
:
Int
=
5000
,
protocol
:
=
"http"
)
{
println
(
"timeout = %d, protocol = %s"
.
format
(
timeout
,
protocol
))
// more code here
}
}
This method can now be called in the following ways:
c
.
makeConnection
()
c
.
makeConnection
(
2000
)
c
.
makeConnection
(
3000
,
"https"
)
The results are demonstrated in the REPL:
scala>val c = new Connection
c: Connection = Connection@385db088 scala>c.makeConnection()
timeout = 5000, protocol = http scala>c.makeConnection(2000)
timeout = 2000, protocol = http scala>c.makeConnection(3000, "https")
timeout = 3000, protocol = https
Note that empty parentheses are used in the first example. Attempting to call this method without parentheses results in an error:
scala> c.makeConnection
<console>:10: error: missing arguments for method makeConnection in Connection;
follow this method with `_' to treat it as a partially applied function
c.makeConnection
^
The reason for this error is discussed in Recipe 9.6.
If you like to call methods with the names of the method
parameters, the method makeConnection
can also be called in these ways:
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.