title | layout | chapter |
---|---|---|
Basic Declarations & Definitions |
default |
4 |
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_k$ cannot be a variable definition. - If
$s_k$ is a value definition, it must be lazy.
Dcl ::= ‘val’ ValDcl
ValDcl ::= ids ‘:’ Type
PatVarDef ::= ‘val’ PatDef
PatDef ::= Pattern2 {‘,’ Pattern2} [‘:’ Type] ‘=’ Expr
ids ::= id {‘,’ id}
A value declaration val $x$: $T$
introduces
A value definition val $x$: $T$ = $e$
defines
Evaluation of the value definition implies evaluation of its
right-hand side lazy
. The
effect of the value definition is to bind lazy
value definition evaluates
its right hand side
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 val $p$ = $e$
is expanded as follows:
- 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.
- If
$p$ has a unique bound variable$x$ :
val $x$ = $e$ match { case $p$ => $x$ }
- If
$p$ has no bound variables:
$e$ match { case $p$ => ()}
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 }
val x$\$$ = mylist match { case x :: xs => (x, xs) }
val x = x$\$$._1
val xs = x$\$$._2
The name of any declared or defined value may not end in _=
.
A value declaration val $x_1 , \ldots , x_n$: $T$
is a shorthand for the
sequence of value declarations val $x_1$: $T$; ...; val $x_n$: $T$
.
A value definition val $p_1 , \ldots , p_n$ = $e$
is a shorthand for the
sequence of value definitions val $p_1$ = $e$; ...; val $p_n$ = $e$
.
A value definition val $p_1 , \ldots , p_n: T$ = $e$
is a shorthand for the
sequence of value definitions val $p_1: T$ = $e$; ...; val $p_n: T$ = $e$
.
Dcl ::= ‘var’ VarDcl
PatVarDef ::= ‘var’ VarDef
VarDcl ::= ids ‘:’ Type
VarDef ::= PatDef
| ids ‘:’ Type ‘=’ ‘_’
A variable declaration var $x$: $T$
is equivalent to the declarations
of both a getter function $x$_=
:
def $x$: $T$
def $x$_= ($y$: $T$): Unit
An implementation of a class may define a declared variable using a variable definition, or by defining the corresponding setter and getter methods.
A variable definition var $x$: $T$ = $e$
introduces a
mutable variable with type
Variable definitions can alternatively have a pattern
as left-hand side. A variable definition
var $p$ = $e$
where val $p$ = $e$
, except that
the free names in
The name of any declared or defined variable may not end in _=
.
A variable definition var $x$: $T$ = _
can appear only as a member of a template.
It introduces a mutable field with type
default | type |
---|---|
0 |
Int or one of its subrange types |
0L |
Long |
0.0f |
Float |
0.0d |
Double |
false |
Boolean |
() |
Unit |
null |
all other types |
When they occur as members of a template, both forms of variable
definition also introduce a getter function $x$_=
which changes the value currently assigned to the variable.
The functions have the same signatures as for a variable declaration.
The template then has these getter and setter functions as
members, whereas the original variable cannot be accessed directly as
a template member.
The following example shows how properties can be
simulated in Scala. It defines a class TimeOfDayVar
of time
values with updatable integer fields representing hours, minutes, and
seconds. Its implementation contains tests that allow only legal
values to be assigned to these fields. The user code, on the other
hand, accesses these fields just like normal variables.
class TimeOfDayVar {
private var h: Int = 0
private var m: Int = 0
private var s: Int = 0
def hours = h
def hours_= (h: Int) = if (0 <= h && h < 24) this.h = h
else throw new DateError()
def minutes = m
def minutes_= (m: Int) = if (0 <= m && m < 60) this.m = m
else throw new DateError()
def seconds = s
def seconds_= (s: Int) = if (0 <= s && s < 60) this.s = s
else throw new DateError()
}
val d = new TimeOfDayVar
d.hours = 8; d.minutes = 30; d.seconds = 0
d.hours = 25 // throws a DateError exception
A variable declaration var $x_1 , \ldots , x_n$: $T$
is a shorthand for the
sequence of variable declarations var $x_1$: $T$; ...; var $x_n$: $T$
.
A variable definition var $x_1 , \ldots , x_n$ = $e$
is a shorthand for the
sequence of variable definitions var $x_1$ = $e$; ...; var $x_n$ = $e$
.
A variable definition var $x_1 , \ldots , x_n: T$ = $e$
is a shorthand for
the sequence of variable definitions
var $x_1: T$ = $e$; ...; var $x_n: T$ = $e$
.
Dcl ::= ‘type’ {nl} TypeDcl
TypeDcl ::= id [TypeParamClause] [‘>:’ Type] [‘<:’ Type]
Def ::= ‘type’ {nl} TypeDef
TypeDef ::= id [TypeParamClause] ‘=’ Type
A type declaration type $t$[$\mathit{tps}\,$] >: $L$ <: $U$
declares
[$\mathit{tps}\,$]
is omitted,
If a type declaration appears as a member declaration of a
type, implementations of the type may implement scala.Nothing
is assumed. If the upper bound scala.Any
is assumed.
A type constructor declaration imposes additional restrictions on the
concrete types for which
The scope of a type parameter extends over the bounds >: $L$ <: $U$
and the type parameter clause
To illustrate nested scoping, these declarations are all equivalent: type t[m[x] <: Bound[x], Bound[x]]
, type t[m[x] <: Bound[x], Bound[y]]
and type t[m[x] <: Bound[x], Bound[_]]
, as the scope of, e.g., the type parameter of t[MutableList, Iterable]
is a valid use of
A type alias type $t$ = $T$
defines type $t$[$\mathit{tps}\,$] = $T$
. The scope
of a type parameter extends over the right hand side
The scope rules for definitions
and type parameters
make it possible that a type name appears in its
own bound or in its right-hand side. However, it is a static error if
a type alias refers recursively to the defined type constructor itself.
That is, the type type $t$[$\mathit{tps}\,$] = $T$
may not
refer directly or indirectly to the name
The following are legal type declarations and definitions:
type IntList = List[Integer]
type T <: Comparable[T]
type Two[A] = Tuple2[A, A]
type MyCollection[+X] <: Iterable[X]
The following are illegal:
type Abs = Comparable[Abs] // recursive type alias
type S <: T // S, T are bounded by themselves.
type T <: S
type T >: Comparable[T.That] // Cannot select from T.
// T is a type, not a value
type MyCollection <: Iterable // Type constructor members must explicitly
// state their type parameters.
If a type alias type $t$[$\mathit{tps}\,$] = $S$
refers to a class type
Suppose we make Pair
an alias of the parameterized class Tuple2
,
as follows:
type Pair[+A, +B] = Tuple2[A, B]
object Pair {
def apply[A, B](x: A, y: B) = Tuple2(x, y)
def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x)
}
As a consequence, for any two types Pair[$S$, $T\,$]
is equivalent to the type Tuple2[$S$, $T\,$]
.
Pair
can also be used as a constructor instead of Tuple2
, as in:
val x: Pair[Int, String] = new Pair(1, "abc")
TypeParamClause ::= ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
VariantTypeParam ::= {Annotation} [‘+’ | ‘-’] TypeParam
TypeParam ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type] [‘:’ Type]
Type parameters appear in type definitions, class definitions, and
function definitions. In this section we consider only type parameter
definitions with lower bounds >: $L$
and upper bounds
<: $U$
whereas a discussion of context bounds
: $U$
and view bounds <% $U$
is deferred to here.
The most general form of a first-order type parameter is
$@a_1 \ldots @a_n$ $\pm$ $t$ >: $L$ <: $U$
.
Here, +
, or
-
. One or more annotations may precede the type parameter.
The names of all type parameters must be pairwise different in their enclosing type parameter clause. The scope of a type parameter includes in each case the whole type parameter clause. Therefore it is possible that a type parameter appears as part of its own bounds or the bounds of other type parameters in the same clause. However, a type parameter may not be bounded directly or indirectly by itself.
A type constructor parameter adds a nested type parameter clause to the type parameter. The most general form of a type constructor parameter is $@a_1\ldots@a_n$ $\pm$ $t[\mathit{tps}\,]$ >: $L$ <: $U$
.
The above scoping restrictions are generalized to the case of nested type parameter clauses, which declare higher-order type parameters. Higher-order type parameters (the type parameters of a type parameter ‘_’
, which is nowhere visible.
Here are some well-formed type parameter clauses:
[S, T]
[@specialized T, U]
[Ex <: Throwable]
[A <: Comparable[B], B <: A]
[A, B >: A, C >: A <: B]
[M[X], N[X]]
[M[_], N[_]] // equivalent to previous clause
[M[X <: Bound[X]], Bound[_]]
[M[+X] <: Iterable[X]]
The following type parameter clauses are illegal:
[A >: A] // illegal, `A' has itself as bound
[A <: B, B <: C, C <: A] // illegal, `A' has itself as bound
[A, B, C >: A <: B] // illegal lower bound `A' of `C' does
// not conform to upper bound `B'.
Variance annotations indicate how instances of parameterized types vary with respect to subtyping. A ‘+’ variance indicates a covariant dependency, a ‘-’ variance indicates a contravariant dependency, and a missing variance indication indicates an invariant dependency.
A variance annotation constrains the way the annotated type variable
may appear in the type or class which binds the type parameter. In a
type definition type $T$[$\mathit{tps}\,$] = $S$
, or a type
declaration type $T$[$\mathit{tps}\,$] >: $L$ <: $U$
type parameters labeled
‘+’ must only appear in covariant position whereas
type parameters labeled ‘-’ must only appear in contravariant
position. Analogously, for a class definition
class $C$[$\mathit{tps}\,$]($\mathit{ps}\,$) extends $T$ { $x$: $S$ => ...}
,
type parameters labeled
‘+’ must only appear in covariant position in the
self type
The variance position of a type parameter in a type or template is defined as follows. Let the opposite of covariance be contravariance, and the opposite of invariance be itself. The top-level of the type or template is always in covariant position. The variance position changes at the following constructs.
- The variance position of a method parameter is the opposite of the variance position of the enclosing parameter clause.
- The variance position of a type parameter is the opposite of the variance position of the enclosing type parameter clause.
- The variance position of the lower bound of a type declaration or type parameter is the opposite of the variance position of the type declaration or parameter.
- The type of a mutable variable is always in invariant position.
- The right-hand side of a type alias is always in invariant position.
- The prefix
$S$ of a type selection$S$#$T$
is always in invariant position. - For a type argument
$T$ of a type$S$[$\ldots T \ldots$ ]
: If the corresponding type parameter is invariant, then$T$ is in invariant position. If the corresponding type parameter is contravariant, the variance position of$T$ is the opposite of the variance position of the enclosing type$S$[$\ldots T \ldots$ ]
.
References to the type parameters in object-private or object-protected values, types, variables, or methods of the class are not checked for their variance position. In these members the type parameter may appear anywhere without restricting its legal variance annotations.
The following variance annotation is legal.
abstract class P[+A, +B] {
def fst: A; def snd: B
}
With this variance annotation, type instances
of
P[IOException, String] <: P[Throwable, AnyRef]
If the members of
abstract class Q[+A, +B](x: A, y: B) {
var fst: A = x // **** error: illegal variance:
var snd: B = y // `A', `B' occur in invariant position.
}
If the mutable variables are object-private, the class definition becomes legal again:
abstract class R[+A, +B](x: A, y: B) {
private[this] var fst: A = x // OK
private[this] var snd: B = y // OK
}
The following variance annotation is illegal, since append
:
abstract class Sequence[+A] {
def append(x: Sequence[A]): Sequence[A]
// **** error: illegal variance:
// `A' occurs in contravariant position.
}
The problem can be avoided by generalizing the type of append
by means of a lower bound:
abstract class Sequence[+A] {
def append[B >: A](x: Sequence[B]): Sequence[B]
}
abstract class OutputChannel[-A] {
def write(x: A): Unit
}
With that annotation, we have that
OutputChannel[AnyRef]
conforms to OutputChannel[String]
.
That is, a
channel on which one can write any object can substitute for a channel
on which one can write only strings.
Dcl ::= ‘def’ FunDcl
FunDcl ::= FunSig ‘:’ Type
Def ::= ‘def’ FunDef
FunDef ::= FunSig [‘:’ Type] ‘=’ Expr
FunSig ::= id [FunTypeParamClause] ParamClauses
FunTypeParamClause ::= ‘[’ TypeParam {‘,’ TypeParam} ‘]’
ParamClauses ::= {ParamClause} [[nl] ‘(’ ‘implicit’ Params ‘)’]
ParamClause ::= [nl] ‘(’ [Params] ‘)’
Params ::= Param {‘,’ Param}
Param ::= {Annotation} id [‘:’ ParamType] [‘=’ Expr]
ParamType ::= Type
| ‘=>’ Type
| Type ‘*’
A function declaration has the form def $f\,\mathit{psig}$: $T$
, where
def $f\,\mathit{psig}$: $T$ = $e$
also includes a function body [$\mathit{tps}\,$]
,
followed by zero or more value parameter clauses
($\mathit{ps}_1$)$\ldots$($\mathit{ps}_n$)
. Such a declaration or definition
introduces a value with a (possibly polymorphic) method type whose
parameter types and result type are as given.
The type of the function body is expected to conform to the function's declared result type, if one is given. If the function definition is not recursive, the result type may be omitted, in which case it is determined from the packed type of the function body.
A type parameter clause
A value parameter clause $x$: $T$
or $x: T = e$
, which bind value
parameters and associate them with their types.
Each value parameter
declaration may optionally define a default argument. The default argument
expression
For every parameter $f\$$default$\$$n
is generated which computes the default argument
expression. Here, [$\mathit{tps}\,$]
and all value parameter clauses
($\mathit{ps}_1$)$\ldots$($\mathit{ps}_{i-1}$)
preceding $f\$$default$\$$n
methods are inaccessible for user programs.
In the method
def compare[T](a: T = 0)(b: T = a) = (a == b)
the default expression 0
is type-checked with an undefined expected
type. When applying compare()
, the default value 0
is inserted
and T
is instantiated to Int
. The methods computing the default
arguments have the form:
def compare$\$$default$\$$1[T]: Int = 0
def compare$\$$default$\$$2[T](a: T): T = a
The scope of a formal value parameter name
A default value which depends on earlier parameters uses the actual arguments if they are provided, not the default arguments.
def f(a: Int = 0)(b: Int = a + 1) = b // OK
// def f(a: Int = 0, b: Int = a + 1) // "error: not found: value a"
f(10)() // returns 11 (not 1)
If an implicit argument is not found by implicit search, it may be supplied using a default argument.
implicit val i: Int = 2
def f(implicit x: Int, s: String = "hi") = s * x
f // "hihi"
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 declaration
def whileLoop (cond: => Boolean) (stat: => Unit): Unit
indicates that both parameters of whileLoop
are evaluated using
call-by-name.
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 ($p_1:T_1 , \ldots , p_n:T_n, p_s:S$*)$U$
is applied to arguments
_*
type
annotation. If ($e_1 , \ldots , e_n, e'$: _*)
, then the type of ($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.
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: _*)
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}$}
.
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) }
}
A class member definition
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 ::= ‘import’ ImportExpr {‘,’ ImportExpr}
ImportExpr ::= StableId ‘.’ (id | ‘_’ | ImportSelectors)
ImportSelectors ::= ‘{’ {ImportSelector ‘,’}
(ImportSelector | ‘_’) ‘}’
ImportSelector ::= id [‘=>’ id | ‘=>’ ‘_’]
An import clause has the form import $p$.$I$
where
{ $x_1$ => $y_1 , \ldots , x_n$ => $y_n$, _ }
for ‘_’
may be absent. It
makes available each importable member $p$.$x_i$
under the unqualified name
$x_i$ => $y_i$
renames
$p$.$x_i$
to
$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 $p$.$x$
to the type name
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”
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$ => $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 import $p$._
is equivalent to
import $p$.{_}
,
i.e. it makes available without qualification all members of 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$
.
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
{ M.add(M.z, M.one) }