Explain the use of 'Default Parameters' in Scala functions.

Instruction: Discuss how default parameters can be used in Scala functions and provide an example.

Context: This question aims to assess the candidate's understanding of default parameters in Scala functions, improving function flexibility and reducing the need for overloaded methods.

Updated

A default parameter supplies an argument when the caller omits it. Named arguments let callers specify later parameters clearly without supplying every earlier optional one.

def formatMessage(recipient: String, body: String,
                  subject: String = "No subject"): String =
  s"To $recipient | $subject | $body"

@main def defaultsExample(): Unit = {
  assert(formatMessage("Ada", "Hello") ==
    "To Ada | No subject | Hello")
  assert(formatMessage(body = "Ready", recipient = "Lin", subject = "Update") ==
    "To Lin | Update | Ready")
  assert(formatMessage("Ada", "Hello", "") == "To Ada |  | Hello")
}

This function formats text; it does not send a message. Defaults reduce the need for otherwise repetitive overloads, while named arguments make a call with several optional values easier to read. Default parameter values

A default expression is evaluated when that argument is omitted at a call, not once when the function is defined. Supplying an empty string or null is an explicit argument, so it does not trigger the default. Keep defaults predictable and avoid expensive or surprising side effects. Overloaded methods cannot independently define conflicting default-argument getters; Scala restricts multiple overloaded alternatives with defaults. Consider how changing a default affects callers and binary compatibility when evolving a published API.

Related Questions