Types

Type              ::=  FunctionArgTypes ‘=>’ Type
                    |  InfixType [ExistentialClause]
FunctionArgTypes  ::=  InfixType
                    |  ‘(’ [ ParamType {‘,’ ParamType } ] ‘)’
ExistentialClause ::=  ‘forSome’ ‘{’ ExistentialDcl
                          {semi ExistentialDcl} ‘}’
ExistentialDcl    ::=  ‘type’ TypeDcl
                    |  ‘val’ ValDcl
InfixType         ::=  CompoundType {id [nl] CompoundType}
CompoundType      ::=  AnnotType {‘with’ AnnotType} [Refinement]
                    |  Refinement
AnnotType         ::=  SimpleType {Annotation}
SimpleType        ::=  SimpleType TypeArgs
                    |  SimpleType ‘#’ id
                    |  StableId
                    |  Path ‘.’ ‘type’
                    |  Literal
                    |  ‘(’ Types ‘)’
TypeArgs          ::=  ‘[’ Types ‘]’
Types             ::=  Type {‘,’ Type}

We distinguish between first-order types and type constructors, which take type parameters and yield types. A subset of first-order types called value types represents sets of (first-class) values. Value types are either concrete or abstract.

Every concrete value type can be represented as a class type, i.e. a type designator that refers to a class or a trait 1^1, or as a compound type representing an intersection of types, possibly with a refinement that further constrains the types of its members.

Abstract value types are introduced by type parameters and abstract type bindings. Parentheses in types can be used for grouping.

Non-value types capture properties of identifiers that are not values. For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type.

Non-value types are expressed indirectly in Scala. E.g., a method type is described by writing down a method signature, which in itself is not a real type, although it gives rise to a corresponding method type. Type constructors are another example, as one can write type Swap[m[_, _], a,b] = m[b, a], but there is no syntax to write the corresponding anonymous type function directly.

1^1 We assume that objects and packages also implicitly define a class (of the same name as the object or package, but inaccessible to user programs).

Paths

Path            ::=  StableId
                  |  [id ‘.’] this
StableId        ::=  id
                  |  Path ‘.’ id
                  |  [id ‘.’] ‘super’ [ClassQualifier] ‘.’ id
ClassQualifier  ::= ‘[’ id ‘]’

Paths are not types themselves, but they can be a part of named types and in that function form a central role in Scala's type system.

A path is one of the following.

  • The empty path ε (which cannot be written explicitly in user programs).
  • C.C.this, where CC references a class. The path this is taken as a shorthand for C.C.this where CC is the name of the class directly enclosing the reference.
  • p.xp.x where pp is a path and xx is a stable member of pp. Stable members are packages or members introduced by object definitions or by value definitions of non-volatile types.
  • C.C.super.x.x or C.C.super[M].x[M].x where CC references a class and xx references a stable member of the super class or designated parent class MM of CC. The prefix super is taken as a shorthand for C.C.super where CC is the name of the class directly enclosing the reference.

A stable identifier is a path which ends in an identifier.

Value Types

Every value in Scala has a type which is of one of the following forms.

Singleton Types

SimpleType  ::=  Path ‘.’ ‘type’

A singleton type is of the form p.p.type. Where pp is a path pointing to a value which conforms to scala.AnyRef, the type denotes the set of values consisting of null and the value denoted by pp (i.e., the value vv for which v eq p). Where the path does not conform to scala.AnyRef the type denotes the set consisting of only the value denoted by pp.

Literal Types

SimpleType  ::=  Literal

A literal type lit is a special kind of singleton type which denotes the single literal value lit. Thus, the type ascription 1: 1 gives the most precise type to the literal value 1: the literal type 1.

At run time, an expression e is considered to have literal type lit if e == lit. Concretely, the result of e.isInstanceOf[lit] and e match { case _ : lit => } is determined by evaluating e == lit.

Literal types are available for all types for which there is dedicated syntax, except Unit. This includes the numeric types (other than Byte and Short which don't currently have syntax), Boolean, Char, String and Symbol.

Stable Types

A stable type is a singleton type, a literal type, or a type that is declared to be a subtype of trait scala.Singleton.

Type Projection

SimpleType  ::=  SimpleType ‘#’ id

A type projection TT#xx references the type member named xx of type TT.

Type Designators

SimpleType  ::=  StableId

A type designator refers to a named value type. It can be simple or qualified. All such type designators are shorthands for type projections.

Specifically, the unqualified type name tt where tt is bound in some class, object, or package CC is taken as a shorthand for C.C.this.type#tt. If tt is not bound in a class, object, or package, then tt is taken as a shorthand for ε.type#tt.

A qualified type designator has the form p.t where p is a path and t is a type name. Such a type designator is equivalent to the type projection p.type#t.

Some type designators and their expansions are listed below. We assume a local type parameter tt, a value maintable with a type member Node and the standard class scala.Int,

DesignatorExpansion
tε.type#t
Intscala.type#Int
scala.Intscala.type#Int
data.maintable.Nodedata.maintable.type#Node

Parameterized Types

SimpleType      ::=  SimpleType TypeArgs
TypeArgs        ::=  ‘[’ Types ‘]’

A parameterized type T[T1,,Tn]T[ T_1 , \ldots , T_n ] consists of a type designator TT and type parameters T1,,TnT_1 , \ldots , T_n where n1n \geq 1.
TT must refer to a type constructor which takes nn type parameters a1,,ana_1 , \ldots , a_n.

Say the type parameters have lower bounds L1,,LnL_1 , \ldots , L_n and upper bounds U1,,UnU_1, \ldots, U_n. The parameterized type is well-formed if each actual type parameter conforms to its bounds, i.e. σLi<:Ti<:σUi\sigma L_i <: T_i <: \sigma U_i where σ\sigma is the substitution [a1:=T1,,an:=Tn][ a_1 := T_1 , \ldots , a_n := T_n ].

Given the partial type definitions:

class TreeMap[A <: Comparable[A], B] {}
class List[A] {}
class I extends Comparable[I] {}

class F[M[_], X] {}
class S[K <: String] {}
class G[M[ Z <: I ], I] {}

the following parameterized types are well formed:

TreeMap[I, String]
List[I]
List[List[Boolean]]

F[List, Int]
G[S, String]

Given the above type definitions, the following types are ill-formed:

TreeMap[I]            // illegal: wrong number of parameters
TreeMap[List[I], Int] // illegal: type parameter not within bound

F[Int, Boolean]       // illegal: Int is not a type constructor
F[TreeMap, Int]       // illegal: TreeMap takes two parameters,
                      //   F expects a constructor taking one
G[S, Int]             // illegal: S constrains its parameter to
                      //   conform to String,
                      // G expects type constructor with a parameter
                      //   that conforms to Int

Tuple Types

SimpleType    ::=   ‘(’ Types ‘)’

A tuple type (T1,,Tn)(T_1 , \ldots , T_n) is an alias for the class scala.Tuplen_n[T1T_1, … , TnT_n], where n2n \geq 2.

Tuple classes are case classes whose fields can be accessed using selectors _1 , … , _n. Their functionality is abstracted in a corresponding Product trait. The n-ary tuple class and product trait are defined at least as follows in the standard Scala library (they might also add other methods and implement other traits).

case class Tuplen_n[+T1T_1,, +TnT_n](_1: T1T_1,, _n: TnT_n)
extends Productn_n[T1T_1,, TnT_n]

trait Productn_n[+T1T_1,, +TnT_n] {
  override def productArity = nn
  def _1: T1T_1def _n: TnT_n
}

Annotated Types

AnnotType  ::=  SimpleType {Annotation}

An annotated type TT a1,,ana_1, \ldots, a_n attaches annotations a1,,ana_1 , \ldots , a_n to the type TT.

The following type adds the @suspendable annotation to the type String:

String @suspendable

Compound Types

CompoundType    ::=  AnnotType {‘with’ AnnotType} [Refinement]
                  |  Refinement
Refinement      ::=  [nl] ‘{’ RefineStat {semi RefineStat} ‘}’
RefineStat      ::=  Dcl
                  |  ‘type’ TypeDef
                  |

A compound type T1T_1 withwith Tn{R}T_n \{ R \} represents objects with members as given in the component types T1,,TnT_1 , \ldots , T_n and the refinement {R}\{ R \}. A refinement {R}\{ R \} contains declarations and type definitions. If a declaration or definition overrides a declaration or definition in one of the component types T1,,TnT_1 , \ldots , T_n, the usual rules for overriding apply; otherwise the declaration or definition is said to be “structural” 2^2.

Within a method declaration in a structural refinement, the type of any value parameter may only refer to type parameters or abstract types that are contained inside the refinement. That is, it must refer either to a type parameter of the method itself, or to a type definition within the refinement. This restriction does not apply to the method's result type.

If no refinement is given, the empty refinement is implicitly added, i.e. T1T_1 withwith TnT_n is a shorthand for T1T_1 withwith Tn{}T_n \{\}.

A compound type may also consist of just a refinement {R}\{ R \} with no preceding component types. Such a type is equivalent to AnyRef {R}\{ R \}.

The following example shows how to declare and use a method which has a parameter type that contains a refinement with structural declarations.

case class Bird (val name: String) extends Object {
  def fly(height: Int) =}
case class Plane (val callsign: String) extends Object {
  def fly(height: Int) =}
def takeoff(
  runway: Int,
  r: { val callsign: String; def fly(height: Int) }
) = {
  tower.print(r.callsign + " requests take-off on runway " + runway)
  tower.read(r.callsign + " is clear for take-off")
  r.fly(1000)
}
val bird = new Bird("Polly the parrot"){ val callsign = name }
val a380 = new Plane("TZ-987")
takeoff(42, bird)
takeoff(89, a380)

Although Bird and Plane do not share any parent class other than Object, the parameter r of method takeoff is defined using a refinement with structural declarations to accept any object that declares a value callsign and a fly method.

2^2 A reference to a structurally defined member (method call or access to a value or variable) may generate binary code that is significantly slower than an equivalent code to a non-structural member.

Infix Types

InfixType     ::=  CompoundType {id [nl] CompoundType}

An infix type T1T_1 op T2T_2 consists of an infix operator op which gets applied to two type operands T1T_1 and T2T_2. The type is equivalent to the type application op[T1,T2][T_1, T_2]. The infix operator op may be an arbitrary identifier.

All type infix operators have the same precedence; parentheses have to be used for grouping. The associativity of a type operator is determined as for term operators: type operators ending in a colon ‘:’ are right-associative; all other operators are left-associative.

In a sequence of consecutive type infix operations t0,op,t1,op2,,opn,tnt_0 , \mathit{op} , t_1 , \mathit{op_2} , \ldots , \mathit{op_n} , t_n, all operators op1,,opn\mathit{op}_1 , \ldots , \mathit{op}_n must have the same associativity. If they are all left-associative, the sequence is interpreted as ((t0op1t1)op2)opntn(\ldots (t_0 \mathit{op_1} t_1) \mathit{op_2} \ldots) \mathit{op_n} t_n, otherwise it is interpreted as t0op1(t1op2(opntn))t_0 \mathit{op_1} (t_1 \mathit{op_2} ( \ldots \mathit{op_n} t_n) \ldots). )

Function Types

Type              ::=  FunctionArgs ‘=>’ Type
FunctionArgs      ::=  InfixType
                    |  ‘(’ [ ParamType {‘,’ ParamType } ] ‘)’

The type (T1,,Tn)U(T_1 , \ldots , T_n) \Rightarrow U represents the set of function values that take arguments of types T1,,TnT_1 , \ldots , Tn and yield results of type UU. In the case of exactly one argument type TUT \Rightarrow U is a shorthand for (T)U(T) \Rightarrow U. An argument type of the form T\Rightarrow T represents a call-by-name parameter of type TT.

Function types associate to the right, e.g. STUS \Rightarrow T \Rightarrow U is the same as S(TU)S \Rightarrow (T \Rightarrow U).

Function types are shorthands for class types that define apply functions. Specifically, the nn-ary function type (T1,,Tn)U(T_1 , \ldots , T_n) \Rightarrow U is a shorthand for the class type Functionn_n[T1-T_1 , ... , TnT_n, UU]. Such class types are defined in the Scala library for nn between 0 and 22 as follows.

package scala
trait Functionn_n[T1-T_1 , ... , Tn-T_n, +U+U] {
  def apply(x1x1: T1T_1 , ... , xnx_n: TnT_n): UU
  override def toString = "<function>"
}

Hence, function types are covariant in their result type and contravariant in their argument types.

Existential Types

Type               ::= InfixType ExistentialClauses
ExistentialClauses ::= ‘forSome’ ‘{’ ExistentialDcl
                      {semi ExistentialDcl} ‘}’
ExistentialDcl     ::= ‘type’ TypeDcl
                    |  ‘val’ ValDcl

An existential type has the form TT forSome { QQ } where QQ is a sequence of type declarations.

Let t1[tps1]&gt;:L1&lt;:U1,,tn[tpsn]&gt;:Ln&lt;:Unt_1[\mathit{tps}_1] &gt;: L_1 &lt;: U_1 , \ldots , t_n[\mathit{tps}_n] &gt;: L_n &lt;: U_n be the types declared in QQ (any of the type parameter sections [ tpsi\mathit{tps}_i ] might be missing). The scope of each type tit_i includes the type TT and the existential clause QQ. The type variables tit_i are said to be bound in the type TT forSome { QQ }. Type variables which occur in a type TT but which are not bound in TT are said to be free in TT.

A type instance of TT forSome { QQ } is a type σT\sigma T where σ\sigma is a substitution over t1,,tnt_1 , \ldots , t_n such that, for each ii, σLi&lt;:σti&lt;:σUi\sigma L_i &lt;: \sigma t_i &lt;: \sigma U_i. The set of values denoted by the existential type TT forSome {&ThinSpace;Q&ThinSpace;\,Q\,} is the union of the set of values of all its type instances.

A skolemization of TT forSome { QQ } is a type instance σT\sigma T, where σ\sigma is the substitution [t1/t1,,tn/tn][t_1&#x27;/t_1 , \ldots , t_n&#x27;/t_n] and each tit_i&#x27; is a fresh abstract type with lower bound σLi\sigma L_i and upper bound σUi\sigma U_i.

Simplification Rules

Existential types obey the following four equivalences:

  1. Multiple for-clauses in an existential type can be merged.
    E.g., TT forSome { QQ } forSome { QQ&#x27; } is equivalent to TT forSome { QQ ; QQ&#x27;}.
  2. Unused quantifications can be dropped.
    E.g., TT forSome { QQ ; QQ&#x27;} where none of the types defined in QQ&#x27; are referred to by TT or QQ, is equivalent to TT forSome {Q Q }.
  3. An empty quantification can be dropped. E.g., TT forSome { } is equivalent to TT.
  4. An existential type TT forSome { QQ } where QQ contains a clause type t[tps]&gt;:L&lt;:Ut[\mathit{tps}] &gt;: L &lt;: U is equivalent to the type TT&#x27; forSome { QQ } where TT&#x27; results from TT by replacing every covariant occurrence of tt in TT by UU and by replacing every contravariant occurrence of tt in TT by LL.
Existential Quantification over Values

As a syntactic convenience, the bindings clause in an existential type may also contain value declarations val xx: TT. An existential type TT forSome { QQ; val xx: S&ThinSpace;S\,;&ThinSpace;Q\,Q&#x27; } is treated as a shorthand for the type TT&#x27; forSome { QQ; type tt <: SS with Singleton; QQ&#x27; }, where tt is a fresh type name and TT&#x27; results from TT by replacing every occurrence of xx.type with tt.

Placeholder Syntax for Existential Types
WildcardType   ::=  ‘_’ TypeBounds

Scala supports a placeholder syntax for existential types. A wildcard type is of the form _&ThickSpace;\;>:&ThinSpace;L&ThinSpace;\,L\,<:&ThinSpace;U\,U. Both bound clauses may be omitted. If a lower bound clause >:&ThinSpace;L\,L is missing, >:&ThinSpace;\,scala.Nothing is assumed. If an upper bound clause <:&ThinSpace;U\,U is missing, <:&ThinSpace;\,scala.Any is assumed.
A wildcard type is a shorthand for an existentially quantified type variable, where the existential quantification is implicit.

A wildcard type must appear as type argument of a parameterized type. Let T=p.c[targs,T,targs]T = p.c[\mathit{targs},T,\mathit{targs}&#x27;] be a parameterized type where targs,targs\mathit{targs}, \mathit{targs}&#x27; may be empty and TT is a wildcard type _&ThickSpace;\;>:&ThinSpace;L&ThinSpace;\,L\,<:&ThinSpace;U\,U. Then TT is equivalent to the existential type

p.c[targs,t,targs]p.c[\mathit{targs},t,\mathit{targs}&#x27;] forSome { type tt >: LL <: UU }

where tt is some fresh type variable. Wildcard types may also appear as parts of infix types, function types, or tuple types. Their expansion is then the expansion in the equivalent parameterized type.

Assume the class definitions

class Ref[T]
abstract class Outer { type T }

Here are some examples of existential types:

Ref[T] forSome { type T <: java.lang.Number }
Ref[x.T] forSome { val x: Outer }
Ref[x_type # T] forSome { type x_type <: Outer with Singleton }

The last two types in this list are equivalent. An alternative formulation of the first type above using wildcard syntax is:

Ref[_ <: java.lang.Number]

The type List[List[_]] is equivalent to the existential type

List[List[t] forSome { type t }]

Assume a covariant type

class List[+T]

The type

List[T] forSome { type T <: java.lang.Number }

is equivalent (by simplification rule 4 above) to

List[java.lang.Number] forSome { type T <: java.lang.Number }

which is in turn equivalent (by simplification rules 2 and 3 above) to List[java.lang.Number].

Non-Value Types

The types explained in the following do not denote sets of values, nor do they appear explicitly in programs. They are introduced in this report as the internal types of defined identifiers.

Method Types

A method type is denoted internally as (Ps)U(\mathit{Ps})U, where (Ps)(\mathit{Ps}) is a sequence of parameter names and types (p1:T1,,pn:Tn)(p_1:T_1 , \ldots , p_n:T_n) for some n0n \geq 0 and UU is a (value or method) type.
This type represents named methods that take arguments named p1,,pnp_1 , \ldots , p_n of types T1,,TnT_1 , \ldots , T_n and that return a result of type UU.

Method types associate to the right: (Ps1)(Ps2)U(\mathit{Ps}_1)(\mathit{Ps}_2)U is treated as (Ps1)((Ps2)U)(\mathit{Ps}_1)((\mathit{Ps}_2)U).

A special case are types of methods without any parameters. They are written here => T. Parameterless methods name expressions that are re-evaluated each time the parameterless method name is referenced.

Method types do not exist as types of values. If a method name is used as a value, its type is implicitly converted to a corresponding function type.

The declarations

def a: Int
def b (x: Int): Boolean
def c (x: Int) (y: String, z: String): String

produce the typings

a: => Int
b: (Int) Boolean
c: (Int) (String, String) String

Polymorphic Method Types

A polymorphic method type is denoted internally as [tps&ThinSpace;\mathit{tps}\,]TT where [tps&ThinSpace;\mathit{tps}\,] is a type parameter section [a1a_1 >: L1L_1 <: U1,,anU_1 , \ldots , a_n >: LnL_n <: UnU_n] for some n0n \geq 0 and TT is a (value or method) type. This type represents named methods that take type arguments S1,,SnS_1 , \ldots , S_n which conform to the lower bounds L1,,LnL_1 , \ldots , L_n and the upper bounds U1,,UnU_1 , \ldots , U_n and that yield results of type TT.

The declarations

def empty[A]: List[A]
def union[A <: Comparable[A]] (x: Set[A], xs: Set[A]): Set[A]

produce the typings

empty : [A >: Nothing <: Any] List[A]
union : [A >: Nothing <: Comparable[A]] (x: Set[A], xs: Set[A]) Set[A]

Type Constructors

A type constructor is represented internally much like a polymorphic method type. [±\pm a1a_1 >: L1L_1 <: U1,,±anU_1 , \ldots , \pm a_n >: LnL_n <: UnU_n] TT represents a type that is expected by a type constructor parameter or an abstract type constructor binding with the corresponding type parameter clause.

Consider this fragment of the Iterable[+X] class:

trait Iterable[+X] {
  def flatMap[newType[+X] <: Iterable[X], S](f: X => newType[S]): newType[S]
}

Conceptually, the type constructor Iterable is a name for the anonymous type [+X] Iterable[X], which may be passed to the newType type constructor parameter in flatMap.

Base Types and Member Definitions

Types of class members depend on the way the members are referenced. Central here are three notions, namely:

  1. the notion of the set of base types of a type TT
  2. the notion of a type TT in some class CC seen from some prefix type SS
  3. the notion of the set of member bindings of some type TT

These notions are defined mutually recursively as follows.

  1. The set of base types of a type is a set of class types, given as follows.

    • The base types of a class type CC with parents T1,,TnT_1 , \ldots , T_n are CC itself, as well as the base types of the compound type T1T_1 with … with TnT_n { RR }.
    • The base types of an aliased type are the base types of its alias.
    • The base types of an abstract type are the base types of its upper bound.
    • The base types of a parameterized type CC[T1,,TnT_1 , \ldots , T_n] are the base types of type CC, where every occurrence of a type parameter aia_i of CC has been replaced by the corresponding parameter type TiT_i.
    • The base types of a singleton type pp.type are the base types of the type of pp.
    • The base types of a compound type T1T_1 with \ldots with TnT_n { RR } are the reduced union of the base classes of all TiT_i's. This means: Let the multi-set S\mathscr{S} be the multi-set-union of the base types of all TiT_i's. If S\mathscr{S} contains several type instances of the same class, say SiS^i#CC[T1i,,TniT^i_1 , \ldots , T^i_n] (iI)(i \in I), then all those instances are replaced by one of them which conforms to all others. It is an error if no such instance exists. It follows that the reduced union, if it exists, produces a set of class types, where different types are instances of different classes.
    • The base types of a type selection SS#TT are determined as follows. If TT is an alias or abstract type, the previous clauses apply. Otherwise, TT must be a (possibly parameterized) class type, which is defined in some class BB. Then the base types of SS#TT are the base types of TT in BB seen from the prefix type SS.
    • The base types of an existential type TT forSome { QQ } are all types SS forSome { QQ } where SS is a base type of TT.
  2. The notion of a type TT in class CC seen from some prefix type SS makes sense only if the prefix type SS has a type instance of class CC as a base type, say SS&#x27;#CC[T1,,TnT_1 , \ldots , T_n]. Then we define as follows.

    • If SS = ϵ\epsilon.type, then TT in CC seen from SS is TT itself.
    • Otherwise, if SS is an existential type SS&#x27; forSome { QQ }, and TT in CC seen from SS&#x27; is TT&#x27;, then TT in CC seen from SS is TT&#x27; forSome {&ThinSpace;Q&ThinSpace;\,Q\,}.
    • Otherwise, if TT is the ii'th type parameter of some class DD, then
      • If SS has a base type DD[U1,,UnU_1 , \ldots , U_n], for some type parameters [U1,,UnU_1 , \ldots , U_n], then TT in CC seen from SS is UiU_i.
      • Otherwise, if CC is defined in a class CC&#x27;, then TT in CC seen from SS is the same as TT in CC&#x27; seen from SS&#x27;.
      • Otherwise, if CC is not defined in another class, then TT in CC seen from SS is TT itself.
    • Otherwise, if TT is the singleton type DD.this.type for some class DD then
      • If DD is a subclass of CC and SS has a type instance of class DD among its base types, then TT in CC seen from SS is SS.
      • Otherwise, if CC is defined in a class CC&#x27;, then TT in CC seen from SS is the same as TT in CC&#x27; seen from SS&#x27;.
      • Otherwise, if CC is not defined in another class, then TT in CC seen from SS is TT itself.
    • If TT is some other type, then the described mapping is performed to all its type components.

    If TT is a possibly parameterized class type, where TT's class is defined in some other class DD, and SS is some prefix type, then we use "TT seen from SS" as a shorthand for "TT in DD seen from SS".

  3. The member bindings of a type TT are

    1. all bindings dd such that there exists a type instance of some class CC among the base types of TT and there exists a definition or declaration dd&#x27; in CC such that dd results from dd&#x27; by replacing every type TT&#x27; in dd&#x27; by TT&#x27; in CC seen from TT
    2. all bindings of the type's refinement, if it has one

The definition of a type projection S#T is the member binding dTd_T of the type T in S. In that case, we also say that S#T is defined by dTd_T.

Relations between types

We define the following relations between types.
NameSymbolicallyInterpretation
Equivalence

TUT \equiv U

TT and UU are interchangeable in all contexts.
Conformance

T&lt;:UT &lt;: U

Type TT conforms to (" is a subtype of") type UU.
Weak Conformance

T&lt;:wUT &lt;:_w U

Augments conformance for primitive numeric types.
Compatibility

Type TT conforms to type UU after conversions.

Equivalence

Equivalence ()(\equiv) between types is the smallest congruence 3^3 such that the following holds:

  • If tt is defined by a type alias type tt = TT, then tt is equivalent to TT.
  • If a path pp has a singleton type qq.type, then pp.type q\equiv q.type.
  • If OO is defined by an object definition, and pp is a path consisting only of package or object selectors and ending in OO, then OO.this.type p\equiv p.type.
  • Two compound types are equivalent if the sequences of their component are pairwise equivalent, and occur in the same order, and their refinements are equivalent. Two refinements are equivalent if they bind the same names and the modifiers, types and bounds of every declared entity are equivalent in both refinements.
  • Two method types are equivalent if:
    • neither are implicit, or they both are 4^4;
    • they have equivalent result types;
    • they have the same number of parameters; and
    • corresponding parameters have equivalent types. Note that the names of parameters do not matter for method type equivalence.
  • Two polymorphic method types are equivalent if they have the same number of type parameters, and, after renaming one set of type parameters by another, the result types as well as lower and upper bounds of corresponding type parameters are equivalent.
  • Two existential types are equivalent if they have the same number of quantifiers, and, after renaming one list of type quantifiers by another, the quantified types as well as lower and upper bounds of corresponding quantifiers are equivalent.
  • Two type constructors are equivalent if they have the same number of type parameters, and, after renaming one list of type parameters by another, the result types as well as variances, lower and upper bounds of corresponding type parameters are equivalent.

3^3 A congruence is an equivalence relation which is closed under formation of contexts.
4^4 A method type is implicit if the parameter section that defines it starts with the implicit keyword.

Conformance

The conformance relation (&lt;:)(&lt;:) is the smallest transitive relation that satisfies the following conditions.

  • Conformance includes equivalence. If TUT \equiv U then T&lt;:UT &lt;: U.
  • For every value type TT, scala.Nothing <: TT <: scala.Any.
  • For every type constructor TT (with any number of type parameters), scala.Nothing <: TT <: scala.Any.
  • For every class type TT such that TT <: scala.AnyRef one has scala.Null <: TT.
  • A type variable or abstract type tt conforms to its upper bound and its lower bound conforms to tt.
  • A class type or parameterized type conforms to any of its base-types.
  • A singleton type pp.type conforms to the type of the path pp.
  • A singleton type pp.type conforms to the type scala.Singleton.
  • A type projection TT#tt conforms to UU#tt if TT conforms to UU.
  • A parameterized type TT[T1T_1 , … , TnT_n] conforms to TT[U1U_1 , … , UnU_n] if the following three conditions hold for i1,,ni \in { 1 , \ldots , n }:
    1. If the ii'th type parameter of TT is declared covariant, then Ti&lt;:UiT_i &lt;: U_i.
    2. If the ii'th type parameter of TT is declared contravariant, then Ui&lt;:TiU_i &lt;: T_i.
    3. If the ii'th type parameter of TT is declared neither covariant nor contravariant, then UiTiU_i \equiv T_i.
  • A compound type T1T_1 with \ldots with TnT_n {R&ThinSpace;R\,} conforms to each of its component types TiT_i.
  • If T&lt;:UiT &lt;: U_i for i1,,ni \in { 1 , \ldots , n } and for every binding dd of a type or value xx in RR there exists a member binding of xx in TT which subsumes dd, then TT conforms to the compound type U1U_1 with \ldots with UnU_n {R&ThinSpace;R\,}.
  • The existential type TT forSome {&ThinSpace;Q&ThinSpace;\,Q\,} conforms to UU if its skolemization conforms to UU.
  • The type TT conforms to the existential type UU forSome {&ThinSpace;Q&ThinSpace;\,Q\,} if TT conforms to one of the type instances of UU forSome {&ThinSpace;Q&ThinSpace;\,Q\,}.
  • If TiTiT_i \equiv T_i&#x27; for i1,,ni \in { 1 , \ldots , n} and UU conforms to UU&#x27; then the method type (p1:T1,,pn:Tn)U(p_1:T_1 , \ldots , p_n:T_n) U conforms to (p1:T1,,pn:Tn)U(p_1&#x27;:T_1&#x27; , \ldots , p_n&#x27;:T_n&#x27;) U&#x27;.
  • The polymorphic type [a1&gt;:L1&lt;:U1,,an&gt;:Ln&lt;:Un]T[a_1 &gt;: L_1 &lt;: U_1 , \ldots , a_n &gt;: L_n &lt;: U_n] T conforms to the polymorphic type [a1&gt;:L1&lt;:U1,,an&gt;:Ln&lt;:Un]T[a_1 &gt;: L_1&#x27; &lt;: U_1&#x27; , \ldots , a_n &gt;: L_n&#x27; &lt;: U_n&#x27;] T&#x27; if, assuming L1&lt;:a1&lt;:U1,,Ln&lt;:an&lt;:UnL_1&#x27; &lt;: a_1 &lt;: U_1&#x27; , \ldots , L_n&#x27; &lt;: a_n &lt;: U_n&#x27; one has T&lt;:TT &lt;: T&#x27; and Li&lt;:LiL_i &lt;: L_i&#x27; and Ui&lt;:UiU_i&#x27; &lt;: U_i for i1,,ni \in { 1 , \ldots , n }.
  • Type constructors TT and TT&#x27; follow a similar discipline. We characterize TT and TT&#x27; by their type parameter clauses [a1,,an][a_1 , \ldots , a_n] and [a1,,an][a_1&#x27; , \ldots , a_n&#x27;], where an aia_i or aia_i&#x27; may include a variance annotation, a higher-order type parameter clause, and bounds. Then, TT conforms to TT&#x27; if any list [t1,,tn][t_1 , \ldots , t_n] -- with declared variances, bounds and higher-order type parameter clauses -- of valid type arguments for TT&#x27; is also a valid list of type arguments for TT and T[t1,,tn]&lt;:T[t1,,tn]T[t_1 , \ldots , t_n] &lt;: T&#x27;[t_1 , \ldots , t_n]. Note that this entails that:
    • The bounds on aia_i must be weaker than the corresponding bounds declared for aia&#x27;_i.
    • The variance of aia_i must match the variance of aia&#x27;_i, where covariance matches covariance, contravariance matches contravariance and any variance matches invariance.
    • Recursively, these restrictions apply to the corresponding higher-order type parameter clauses of aia_i and aia&#x27;_i.

A declaration or definition in some compound type of class type CC subsumes another declaration of the same name in some compound type or class type CC&#x27;, if one of the following holds.

  • A value declaration or definition that defines a name xx with type TT subsumes a value or method declaration that defines xx with type TT&#x27;, provided T&lt;:TT &lt;: T&#x27;.
  • A method declaration or definition that defines a name xx with type TT subsumes a method declaration that defines xx with type TT&#x27;, provided T&lt;:TT &lt;: T&#x27;.
  • A type alias type tt[T1T_1 , … , TnT_n] = TT subsumes a type alias type tt[T1T_1 , … , TnT_n] = TT&#x27; if TTT \equiv T&#x27;.
  • A type declaration type tt[T1T_1 , … , TnT_n] >: LL <: UU subsumes a type declaration type tt[T1T_1 , … , TnT_n] >: LL&#x27; <: UU&#x27; if L&lt;:LL&#x27; &lt;: L and U&lt;:UU &lt;: U&#x27;.
  • A type or class definition that binds a type name tt subsumes an abstract type declaration type t[T1T_1 , … , TnT_n] >: L <: U if L&lt;:t&lt;:UL &lt;: t &lt;: U.
Least upper bounds and greatest lower bounds

The (&lt;:)(&lt;:) relation forms pre-order between types, i.e. it is transitive and reflexive. This allows us to define least upper bounds and greatest lower bounds of a set of types in terms of that order. The least upper bound or greatest lower bound of a set of types does not always exist. For instance, consider the class definitions:

class A[+T] {}
class B extends A[B]
class C extends A[C]

Then the types A[Any], A[A[Any]], A[A[A[Any]]], ... form a descending sequence of upper bounds for B and C. The least upper bound would be the infinite limit of that sequence, which does not exist as a Scala type. Since cases like this are in general impossible to detect, a Scala compiler is free to reject a term which has a type specified as a least upper or greatest lower bound, and that bound would be more complex than some compiler-set limit [^4].

The least upper bound or greatest lower bound might also not be unique. For instance A with B and B with A are both greatest lower bounds of A and B. If there are several least upper bounds or greatest lower bounds, the Scala compiler is free to pick any one of them.

[^4]: The current Scala compiler limits the nesting level of parameterization in such bounds to be at most two deeper than the maximum nesting level of the operand types

Weak Conformance

In some situations Scala uses a more general conformance relation. A type SS weakly conforms to a type TT, written S&lt;:wTS &lt;:_w T, if S&lt;:TS &lt;: T or both SS and TT are primitive number types and SS precedes TT in the following ordering.

Byte  &lt;:w&lt;:_w Short
Short &lt;:w&lt;:_w Int
Char  &lt;:w&lt;:_w Int
Int   &lt;:w&lt;:_w Long
Long  &lt;:w&lt;:_w Float
Float &lt;:w&lt;:_w Double

A weak least upper bound is a least upper bound with respect to weak conformance.

Compatibility

A type TT is compatible to a type UU if TT (or its corresponding function type) weakly conforms to UU after applying eta-expansion. If TT is a method type, it's converted to the corresponding function type. If the types do not weakly conform, the following alternatives are checked in order:

  • view application: there's an implicit view from TT to UU
  • dropping by-name modifiers: if UU is of the shape =&gt;U=&gt; U&#x27; (and TT is not), T&lt;:wUT &lt;:_w U&#x27;
  • SAM conversion: if TT corresponds to a function type, and UU declares a single abstract method whose type corresponds to the function type UU&#x27;, T&lt;:wUT &lt;:_w U&#x27;
Function compatibility via SAM conversion

Given the definitions

def foo(x: Int => String): Unit
def foo(x: ToString): Unit

trait ToString { def convert(x: Int): String }

The application foo((x: Int) => x.toString) resolves to the first overload, as it's more specific:

  • Int => String is compatible to ToString -- when expecting a value of type ToString, you may pass a function literal from Int to String, as it will be SAM-converted to said function;
  • ToString is not compatible to Int => String -- when expecting a function from Int to String, you may not pass a ToString.

Volatile Types

Type volatility approximates the possibility that a type parameter or abstract type instance of a type does not have any non-null values. A value member of a volatile type cannot appear in a path.

A type is volatile if it falls into one of four categories:

A compound type T1T_1 with … with TnT_n {R&ThinSpace;R\,} is volatile if one of the following two conditions hold.

  1. One of T2,,TnT_2 , \ldots , T_n is a type parameter or abstract type, or
  2. T1T_1 is an abstract type and and either the refinement RR or a type TjT_j for j&gt;1j &gt; 1 contributes an abstract member to the compound type, or
  3. one of T1,,TnT_1 , \ldots , T_n is a singleton type.

Here, a type SS contributes an abstract member to a type TT if SS contains an abstract member that is also a member of TT. A refinement RR contributes an abstract member to a type TT if RR contains an abstract declaration which is also a member of TT.

A type designator is volatile if it is an alias of a volatile type, or if it designates a type parameter or abstract type that has a volatile type as its upper bound.

A singleton type pp.type is volatile, if the underlying type of path pp is volatile.

An existential type TT forSome {&ThinSpace;Q&ThinSpace;\,Q\,} is volatile if TT is volatile.

Type Erasure

A type is called generic if it contains type arguments or type variables. Type erasure is a mapping from (possibly generic) types to non-generic types. We write T|T| for the erasure of type TT. The erasure mapping is defined as follows.

  • The erasure of an alias type is the erasure of its right-hand side.
  • The erasure of an abstract type is the erasure of its upper bound.
  • The erasure of the parameterized type scala.Array[T1][T_1] is scala.Array[T1][|T_1|].
  • The erasure of every other parameterized type T[T1,,Tn]T[T_1 , \ldots , T_n] is T|T|.
  • The erasure of a singleton type pp.type is the erasure of the type of pp.
  • The erasure of a type projection TT#xx is |TT|#xx.
  • The erasure of a compound type T1T_1 with \ldots with TnT_n {R&ThinSpace;R\,} is the erasure of the intersection dominator of T1,,TnT_1 , \ldots , T_n.
  • The erasure of an existential type TT forSome {&ThinSpace;Q&ThinSpace;\,Q\,} is T|T|.

The intersection dominator of a list of types T1,,TnT_1 , \ldots , T_n is computed as follows. Let Ti1,,TimT_{i_1} , \ldots , T_{i_m} be the subsequence of types TiT_i which are not supertypes of some other type TjT_j. If this subsequence contains a type designator TcT_c that refers to a class which is not a trait, the intersection dominator is TcT_c. Otherwise, the intersection dominator is the first element of the subsequence, Ti1T_{i_1}.