Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core calculus in scala type system (recursion)

Tags:

scala

How does the Typer in the scala compiler verify the following:

class D[T <: D[T]]
class E extends D[E]

The upper bound D[T] of class D's type parameter must be compatible with E. Type E is not equivalent to D, so its base type D will be checked. Because the type constructors of E's base type and D are equal, the bounds must be checked. And here comes the recursion. The Core Calculus does not handle this.

like image 764
tim Avatar asked Feb 20 '11 15:02

tim


2 Answers

1) Start with

E extends D[E]

2) Extends implies subtyping in Scala, so

E <: D[E]        

3) Because of the definition "class D[T <: D[T]]", the requirement on T for any D[T] is that T <: D[T]. Step 2 said E must be able to be able to be plugged in to T, so it better match that requirement. Substituting E for T we get the requirement that

E <: D[E]

We already showed E <: D[E] in step 2. We're done.

like image 97
James Iry Avatar answered Nov 09 '22 09:11

James Iry


No real answer, just two remarks: This pattern is known as CRTP, and it works in Java, too (see java.lang.Enum)

like image 20
Landei Avatar answered Nov 09 '22 09:11

Landei