Created by rytz on 2009-06-03. Updated: 2009-06-04, 16:07

Scala 2.8 offers the possibility to call methods using "named arguments", which means specifying the arguments based on the parameter names (instead of the parameter positions). Named arguments help to avoid confusing parameters of the same type and improve code readability.

def resize ( width : Int , height : Int ) = { ... } resize ( width = 120 , height = 42 )

Furthermore, Scala 2.8 allows providing default arguments on method parameters. In current versions of Scala, default arguments have to be implemented manually using method overloading. This causes some level of code duplication which can be avoided using default arguments.

def f ( elems : List [ Int ] , x : Int = 0 , cond : Boolean = true ) f ( List ( 1 ) ) f ( Nil , cond = false )

The example also shows how named arguments allow to selectively use defaults of a method: the second application to f uses the default for x, but not the one for cond.

Compiler-generated copy methods

One very useful application of named and default arguments are the compiler-generated "copy" methods in case classes, which allow to create modified copies of an instance using a lightweight syntax. The copy method takes the same type and value parameters as the primary constructor of the case class, and every parameter defaults to the corresponding constructor parameter:

case class A [ T ] ( a : T , b : Int ) { // def copy[T'](a: T' = this.a, b: Int = this.b): A[T'] = new A[T'](a, b) } val a1 : A [ Int ] = A ( 1 , 2 ) val a2 : A [ String ] = a1. copy ( a = "someString" )

Download a recent nightly build (linux-mac / windows) to try out named and default arguments yourself! To read more about named and default arguments, have a look at the corresponding SID.