Named and Default Arguments for Polymorphic Object-Oriented Languages

Named and Default Arguments for Polymorphic Object-Oriented Languages

Named and default arguments for polymorphic object-oriented languages A discussion on the design implemented in the Scala language Lukas Rytz Martin Odersky Programming Methods Laboratory Programming Methods Laboratory École Polytechnique Fédérale de Lausanne École Polytechnique Fédérale de Lausanne lukas.rytz@epfl.ch martin.odersky@epfl.ch ABSTRACT The use of named arguments improves code readability by This article describes the design and implementation of named making the role of an argument explicit, and it eliminates and default arguments in the Scala programming language. the risk of confusing the positions of parameters of the same While these features are available in many other languages type, an error which cannot be caught by a type system there are significant differences in the actual implementa- otherwise. Compare the following method applications: tions. We present a design that unifies the most reason- frame.setSize(200, 300) // which one is the height? able properties for an object-oriented language and provides frame.setSize(height = 200, width = 300) new possibilities by allowing default arguments on generic and implicit parameters. We also present a solution for the Another important application for named arguments comes problem of writing a lightweight generic update function for up when using them in conjunction with default arguments, algebraic datatypes. the second concept discussed in this article. A language with default arguments allows specifying default values for Categories and Subject Descriptors the parameters of a method. These defaults are used when- ever a method application leaves some of the parameters D.3.3 [Programming Languages]: Language Constructs undefined. and Features|Procedures, functions, and subroutines With positional arguments, the only possibility to use de- faults is to leave some parameters at the end undefined. General Terms With named arguments it is possible to provide a value for Languages, Design an arbitrary subset of the parameters and use the defaults for the others. Keywords Named and default arguments are very common features and can be found in a large number of programming lan- Named arguments, default arguments, Scala guages (see section 4). We investigate how they are im- plemented in other languages and analyze how the different 1. INTRODUCTION design choices affect the interaction with other language fea- When applying a method to a set of arguments, every ar- tures such as method overriding, virtual method calls and gument expression has to be mapped to one of the method's overloading resolution. We present two new use cases for parameters. In most programming languages this mapping default arguments by allowing to use them on parameters of is defined by the position of the argument expressions in a generic type and on implicit parameters. the argument list (i.e. the nth argument defines the nth pa- The rest of this paper is structured as follows. Section rameter of the method), in which case the arguments are 2 discusses the design choices for implementing named and called positional. An alternative is using named arguments, default arguments. In section 3 we explain the compilation where the programmer explicitly mentions the parameter technique used in Scala. Section 4 compares our implemen- name that an argument expression defines. tation with other languages, and section 5 concludes. The additional verbosity of named arguments is worth- while in applications of methods with a large number of 2. DESIGN CHOICES parameters or with multiple parameters of the same type. A central constraint when extending an existing language with named and default arguments is source compatibility: the new feature should not invalidate any existing code. But Permission to make digital or hard copies of all or part of this work for even with this restriction there are a number of design deci- personal or classroom use is granted without fee provided that copies are sion to be made. not made or distributed for profit or commercial advantage and that copies While this section provides a qualitative discussion on bear this notice and the full citation on the first page. To copy otherwise, to Scala's design of named and default arguments, a more pre- republish, to post on servers or to redistribute to lists, requires prior specific cise description of the semantics, defined by a translation permission and/or a fee. SAC’10 March 22-26, 2010, Sierre, Switzerland. into equivalent code without parameter names or defaults, Copyright 2010 ACM 978-1-60558-638-0/10/03 ...$10.00. can be found in the Scala language specification [11]. 2.1 Flexibility 2.3 Interaction with other features Our implementation of named and default arguments is This section describes how an elaborate integration of designed to provide a high degree of flexibility for the pro- named and default arguments with other language features grammer. A first fundamental decision is whether the use enables a number of useful programming patterns. of named arguments should be optional or not. We decided to make them optional because this gives the programmer 2.3.1 Curried method definitions more flexibility when calling a method, and it does not force In Scala, methods can have multiple parameter lists. Method him to chose which parameters should be named when defin- definitions with more than one parameter list are called cur- ing a method. It also allows using named arguments when ried because they allow partial application. calling a method that was written before named arguments When writing a curried method definition, default argu- were available in the language, because there is no change ments can depend on earlier parameters of the same method. in the way parameters are defined. In other words, the parameters are visible not only in the A disadvantage of enabling named arguments on all pa- method body, but also in all subsequent parameter lists. rameters is that parameter names immediately become part This enables the programmer to specify meaningful default of the public interface of a method, and changing them can arguments in some additional situations: invalidate client code. This is also true for source code which was written before named arguments were available in the def resizeImage(i: Image)(h: Int = i.height, language. Presumably, programmers were less careful in w: Int = i.width) = { .. } choosing parameter names in the past because they expected them to be private. To solve the ambiguity between a partially applied method and a method application using default arguments, Scala When using named arguments, Scala allows to specify the uses default arguments only for completing underspecified parameters in a different order than in the method defini- arguments lists. In order to use the default arguments of the tion. We also allow mixing positional and named arguments, above definition, an empty argument list has to be provided, in this case all positional arguments have to appear left of i.e. resizeImage(myImage)(). the named arguments. Unlike for instance C# 4.0 [4] where only the last parameters of a method are allowed to have de- 2.3.2 Overriding and virtual method calls faults, any parameter can have a default argument in Scala. When a method is being overridden in a subclass, the pa- rameter names of the overriding method do not need to be 2.2 Evaluation order the same as in the superclass. For type-checking an appli- Unlike OCaml [10] or ADA95 [8], Scala has a definite eval- cation which uses named arguments, the static type of the uation order for method arguments. Thus, we need to define method determines which names have to be used. However an evaluation order in the presence of named and default the actual method which is called is still resolved dynam- arguments. Given that positional arguments are evaluated ically: even if an application uses the parameter names of left-to-right, the same is done for named arguments. So in a superclass, an implementation of a subclass with different parameter names might be called. The following example the following example, a() is always evaluated before b(), no matter what the order of parameters in the method def- illustrates this behavior: inition is. trait A{ def f(a: Int, b: Int): Int = a + b m(y = a(), x = b()) } When an argument list of an application is completed with class B extends A{ default arguments, the default expressions are evaluated af- override def f(x: Int, y: Int) = x - y ter the specified arguments of that parameter list. The de- } val new fault arguments which are used in a particular application a: A = B a.f(b = 2, a = 3) // returns 1 behave just like specified arguments: they are evaluated ex- actly once, except if the corresponding parameter is a by- With the ability to choose parameter names freely it is name parameter, in which case they are evaluated every time possible to re-use a parameter name from the superclass for the method body refers to the parameter. Default expres- a different parameter in the subclass. Doing so should be sions which are not used in a method application are not avoided because it can can lead to unexpected errors when evaluated. changing a type to a more specific one: If an application has multiple argument lists (see 2.3.1), these are always evaluated left-to-right. This implies that trait A{ def f(a: Int, b: Int): Int } default expressions used in the first argument list are evalu- class B extends A{ def f(b: Int, a: Int) = b - a } ated before any arguments of the second argument list. The following, slightly tricky example illustrates evalu- val b = new B ation of default arguments. First, the default expression (b: A).f(a = 3, b = 2) // returns 1 {i += 1; i} is evaluated, then the specified argument i, and b.f(a = 3, b = 2) // returns -1 finally the default expression {i += 2; i}.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    6 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us