# Basic Declarations and Definitions

Dcl         ::=  ‘val’ ValDcl
|  ‘var’ VarDcl
|  ‘def’ FunDcl
|  ‘type’ {nl} TypeDcl
PatVarDef   ::=  ‘val’ PatDef
|  ‘var’ VarDef
Def         ::=  PatVarDef
|  ‘def’ FunDef
|  ‘type’ {nl} TypeDef
|  TmplDef

A declaration introduces names and assigns them types. It can form part of a class definition or of a refinement in a compound type.

A definition introduces names that denote terms or types. It can form part of an object or class definition or it can be local to a block. Both declarations and definitions produce bindings that associate type names with type definitions or bounds, and that associate term names with types.

The scope of a name introduced by a declaration or definition is the whole statement sequence containing the binding. However, there is a restriction on forward references in blocks: In a statement sequence $s_1 \ldots s_n$ making up a block, if a simple name in $s_i$ refers to an entity defined by $s_j$ where $j \geq i$, then for all $s_k$ between and including $s_i$ and $s_j$,

• $s_k$ cannot be a variable definition.
• If $s_k$ is a value definition, it must be lazy.

## Value Declarations and Definitions

Dcl          ::=  ‘val’ ValDcl
ValDcl       ::=  ids ‘:’ Type
PatVarDef    ::=  ‘val’ PatDef
PatDef       ::=  Pattern2 {‘,’ Pattern2} [‘:’ Type] ‘=’ Expr
ids          ::=  id {‘,’ id}

A value declaration val $x$: $T$ introduces $x$ as a name of a value of type $T$.

A value definition val $x$: $T$ = $e$ defines $x$ as a name of the value that results from the evaluation of $e$. If the value definition is not recursive, the type $T$ may be omitted, in which case the packed type of expression $e$ is assumed. If a type $T$ is given, then $e$ is expected to conform to it.

Evaluation of the value definition implies evaluation of its right-hand side $e$, unless it has the modifier lazy. The effect of the value definition is to bind $x$ to the value of $e$ converted to type $T$. A lazy value definition evaluates its right hand side $e$ the first time the value is accessed.

A constant value definition is of the form

final val x = e

where e is a constant expression. The final modifier must be present and no type annotation may be given. References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the definition's right-hand side e.

Value definitions can alternatively have a pattern as left-hand side. If $p$ is some pattern other than a simple name or a name followed by a colon and a type, then the value definition val $p$ = $e$ is expanded as follows:

1. If the pattern $p$ has bound variables $x_1 , \ldots , x_n$, where $n > 1$:
val $\$ x$=$e$match {case$p$=> ($x_1 , \ldots , x_n$)} val$x_1$=$\$x$._1
$\ldots$
val $x_n$ = $\$ x$._n . Here,$\$x$ is a fresh name.

1. If $p$ has a unique bound variable $x$:
val $x$ = $e$ match { case $p$ => $x$ }
1. If $p$ has no bound variables:
$e$ match { case $p$ => ()}
###### Example

The following are examples of value definitions

val pi = 3.1415
val pi: Double = 3.1415   // equivalent to first definition
val Some(x) = f()         // a pattern definition
val x :: xs = mylist      // an infix pattern definition

The last two definitions have the following expansions.

val x = f() match { case Some(x) => x }

### By-Name Parameters

ParamType          ::=  ‘=>’ Type

The type of a value parameter may be prefixed by =>, e.g. $x$: => $T$. The type of such a parameter is then the parameterless method type => $T$. This indicates that the corresponding argument is not evaluated at the point of function application, but instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.

The by-name modifier is disallowed for parameters of classes that carry a val or var prefix, including parameters of case classes for which a val prefix is implicitly generated. The by-name modifier is also disallowed for implicit parameters.

###### Example

The declaration

def whileLoop (cond: => Boolean) (stat: => Unit): Unit

indicates that both parameters of whileLoop are evaluated using call-by-name.

### Repeated Parameters

ParamType          ::=  Type ‘*’

The last value parameter of a parameter section may be suffixed by '*', e.g. (..., $x$:$T$*). The type of such a repeated parameter inside the method is then the sequence type scala.Seq[$T$]. Methods with repeated parameters $T$* take a variable number of arguments of type $T$. That is, if a method $m$ with type ($p_1:T_1 , \ldots , p_n:T_n, p_s:S$*)$U$ is applied to arguments $(e_1 , \ldots , e_k)$ where $k \geq n$, then $m$ is taken in that application to have type $(p_1:T_1 , \ldots , p_n:T_n, p_s:S , \ldots , p_{s'}S)U$, with $k - n$ occurrences of type $S$ where any parameter names beyond $p_s$ are fresh. The only exception to this rule is if the last argument is marked to be a sequence argument via a _* type annotation. If $m$ above is applied to arguments ($e_1 , \ldots , e_n, e'$: _*), then the type of $m$ in that application is taken to be ($p_1:T_1, \ldots , p_n:T_n,p_{s}:$scala.Seq[$S$]).

It is not allowed to define any default arguments in a parameter section with a repeated parameter.

###### Example

The following method definition computes the sum of the squares of a variable number of integer arguments.

def sum(args: Int*) = {
var result = 0
for (arg <- args) result += arg
result
}

The following applications of this method yield 0, 1, 6, in that order.

sum()
sum(1)
sum(1, 2, 3)

Furthermore, assume the definition:

val xs = List(1, 2, 3)

The following application of method sum is ill-formed:

sum(xs)       // ***** error: expected: Int, found: List[Int]

By contrast, the following application is well formed and yields again the result 6:

sum(xs: _*)

### Procedures

FunDcl   ::=  FunSig
FunDef   ::=  FunSig [nl] ‘{’ Block ‘}’

Special syntax exists for procedures, i.e. functions that return the Unit value (). A procedure declaration is a function declaration where the result type is omitted. The result type is then implicitly completed to the Unit type. E.g., def $f$($\mathit{ps}$) is equivalent to def $f$($\mathit{ps}$): Unit.

A procedure definition is a function definition where the result type and the equals sign are omitted; its defining expression must be a block. E.g., def $f$($\mathit{ps}$) {$\mathit{stats}$} is equivalent to def $f$($\mathit{ps}$): Unit = {$\mathit{stats}$}.

###### Example

Here is a declaration and a definition of a procedure named write:

trait Writer {
def write(str: String)
}
object Terminal extends Writer {
def write(str: String) { System.out.println(str) }
}

The code above is implicitly completed to the following code:

trait Writer {
def write(str: String): Unit
}
object Terminal extends Writer {
def write(str: String): Unit = { System.out.println(str) }
}

### Method Return Type Inference

A class member definition $m$ that overrides some other function $m'$ in a base class of $C$ may leave out the return type, even if it is recursive. In this case, the return type $R'$ of the overridden function $m'$, seen as a member of $C$, is taken as the return type of $m$ for each recursive invocation of $m$. That way, a type $R$ for the right-hand side of $m$ can be determined, which is then taken as the return type of $m$. Note that $R$ may be different from $R'$, as long as $R$ conforms to $R'$.

###### Example

Assume the following definitions:

trait I {
def factorial(x: Int): Int
}
class C extends I {
def factorial(x: Int) = if (x == 0) 1 else x * factorial(x - 1)
}

Here, it is OK to leave out the result type of factorial in C, even though the method is recursive.

## Import Clauses

Import          ::= ‘import’ ImportExpr {‘,’ ImportExpr}
ImportExpr      ::= StableId ‘.’ (id | ‘_’ | ImportSelectors)
ImportSelectors ::= ‘{’ {ImportSelector ‘,’}
(ImportSelector | ‘_’) ‘}’
ImportSelector  ::= id [‘=>’ id | ‘=>’ ‘_’]

An import clause has the form import $p$.$I$ where $p$ is a stable identifier and $I$ is an import expression. The import expression determines a set of names of importable members of $p$ which are made available without qualification. A member $m$ of $p$ is importable if it is not object-private. The most general form of an import expression is a list of import selectors

{ $x_1$ => $y_1 , \ldots , x_n$ => $y_n$, _ }

for $n \geq 0$, where the final wildcard ‘_’ may be absent. It makes available each importable member $p$.$x_i$ under the unqualified name $y_i$. I.e. every import selector $x_i$ => $y_i$ renames $p$.$x_i$ to $y_i$. If a final wildcard is present, all importable members $z$ of $p$ other than $x_1 , \ldots , x_n,y_1 , \ldots , y_n$ are also made available under their own unqualified names.

Import selectors work in the same way for type and term members. For instance, an import clause import $p$.{$x$ => $y\,$} renames the term name $p$.$x$ to the term name $y$ and the type name $p$.$x$ to the type name $y$. At least one of these two names must reference an importable member of $p$.

If the target in an import selector is a wildcard, the import selector hides access to the source member. For instance, the import selector $x$ => _ “renames” $x$ to the wildcard symbol (which is unaccessible as a name in user programs), and thereby effectively prevents unqualified access to $x$. This is useful if there is a final wildcard in the same import selector list, which imports all members not mentioned in previous import selectors.

The scope of a binding introduced by an import-clause starts immediately after the import clause and extends to the end of the enclosing block, template, package clause, or compilation unit, whichever comes first.

Several shorthands exist. An import selector may be just a simple name $x$. In this case, $x$ is imported without renaming, so the import selector is equivalent to $x$ => $x$. Furthermore, it is possible to replace the whole import selector list by a single identifier or wildcard. The import clause import $p$.$x$ is equivalent to import $p$.{$x\,$}, i.e. it makes available without qualification the member $x$ of $p$. The import clause import $p$._ is equivalent to import $p$.{_}, i.e. it makes available without qualification all members of $p$ (this is analogous to import $p$.* in Java).

An import clause with multiple import expressions import $p_1$.$I_1 , \ldots , p_n$.$I_n$ is interpreted as a sequence of import clauses import $p_1$.$I_1$; $\ldots$; import $p_n$.$I_n$.

###### Example

Consider the object definition:

object M {
def z = 0, one = 1
def add(x: Int, y: Int): Int = x + y
}

Then the block

{ import M.{one, z => zero, _}; add(zero, one) }

is equivalent to the block