Optional Parameters in Scala


One of the many cool features Scala provides over Java is the ability to provide default values for parameters. Such parameters become optional and the callers can invoke the method without providing a value for those parameters. This is useful in cases wherever you overload methods in Java – like constructor chaining, releasing a newer version of an API which takes additional parameter etc.

For example consider this method which takes two parameters firstName and lastName.

def printName(firstName: String, lastName: String): Unit = {
  println(firstName + " " + lastName)
}

This method can be invoked in following way

printName("Anil", "Kurian")

At a later point of time if you want to modify this method to accept a middleName, which is optional, you can do it like this.

def printName(firstName: String, lastName: String, middleName: String = ""): Unit = {
  if (middleName.isEmpty)
    println(firstName + " " + lastName)
  else
    println(firstName + " " + middleName + " " + lastName)
}

The new version of the method can be invoked by providing or not providing the last parameter middleName. This way none of the existing code will complain.

printName("Anil", "Kurian")
printName("Anil", "Kurian", "G")

If you have more than one optional parameter like this:

def printName(firstName: String, lastName: String="", middleName: String = ""): Unit = {
  if (middleName.isEmpty)
    println(firstName + " " + lastName)
  else
    println(firstName + " " + middleName + " " + lastName)
}

You can name the argument in this case so that Scala will supply default value for the remaining. All the following four invocation combinations are possible for this version of printName()

printName("Anil")
printName("Anil", "Kurian")
printName("Anil", "Kurian", "G")
printName("Anil", middleName="G")  // named parameter

Sample source code is available here

Advertisement

2 thoughts on “Optional Parameters in Scala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s