5.4. Using Parameter Names When Calling a Method

Problem

You prefer a coding style where you specify the method parameter names when calling a method.

Solution

The general syntax for calling a method with named parameters is this:

methodName(param1=value1, param2=value2, ...)

This is demonstrated in the following example.

Given this definition of a Pizza class:

class Pizza {
  var crustSize = 12
  var crustType = "Thin"
  def update(crustSize: Int, crustType: String) {
    this.crustSize = crustSize
    this.crustType = crustType
  }
  override def toString = {
    "A %d inch %s crust pizza.".format(crustSize, crustType)
  }
}

you can create a Pizza:

val p = new Pizza

You can then update the Pizza, specifying the field names and corresponding values when you call the update method:

p.update(crustSize = 16, crustType = "Thick")

This approach has the added benefit that you can place the fields in any order:

p.update(crustType = "Pan", crustSize = 14)

Discussion

You can confirm that this example works by running it in the Scala REPL:

scala> val p = new Pizza
p: Pizza = A 12 inch Thin crust pizza.

scala> p.updatePizza(crustSize = 16, crustType = "Thick")

scala> println(p)
A 16 inch Thick crust pizza.

scala> p.updatePizza(crustType = "Pan", crustSize = 14)

scala> println(p)
A 14 inch Pan crust pizza.

The ability to use named parameters when calling a method is available in other languages, including Objective-C. Although this approach is more verbose, it can also be more readable.

This technique is especially useful when several ...

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.