Default values
A parameter that may be left out, and the value it takes when nothing is said.
A parameter can carry a value that it will take if the call says nothing.
@entry(start)
object MyProgram {
start() {
self.greet(name: "Simon Magus");
self.greet(name: "Simon Magus", greeting: "Hi");
self.greet(name: "Simon Magus", greeting: "Good evening");
}
greet(name: str, greeting: str := "Hello") {
Console.print(text: $"{greeting}, {name}!");
}
}
Three calls, a single method, and the first one passes only one argument out of two.
The value sits in the declaration
greet(name: str, greeting: str := "Hello") {
It is the := of section 2.1, in its usual place: to the right, the value that is taken. name
stays compulsory — the call must supply it. greeting becomes optional: without it, the
method works with "Hello".
One body, then, for what would have taken two nearly identical methods. And the default is written where you look for it: in the signature, not buried in a line of the body.
An optional parameter is passed by name
Nothing compels you to name it, but everything pushes you to. A default is nearly always placed
after the compulsory parameters, and you have known since section 1.2.1 that a positional
argument following a named one is refused (T027). Naming the optional one settles the question
without your having to think about it:
self.greet(name: "Simon Magus", greeting: "Hi");
It is also what makes the call readable. self.greet("Simon Magus", "Hi") works, but you have to
know the order of the parameters to tell which of the two texts is the greeting.
Your turn
- Remove
greeting:from the last two calls: three identical “Hello”s. - Change the default to
"Greetings"and run only the first call. A single line changed alters every call that stayed silent. - Give
namea default too, then callself.greet();with nothing at all. A method whose every parameter has a default is called empty-handed.