Skip to content

Commit

Permalink
Update virtual_type.md
Browse files Browse the repository at this point in the history
This takes the better manual documentation from the nit website.
  • Loading branch information
dullin committed Aug 19, 2024
1 parent da4205e commit 0c45b71
Showing 1 changed file with 42 additions and 14 deletions.
56 changes: 42 additions & 14 deletions doc/manual/virtual_type.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,48 @@
# Virtual Types

`type` declares a virtual types in a class. A bound type is
mandatory. Virtual types can then be used as regular types in the class
and its subclasses. Subclasses can also redefine it with a more specific
bound type. One can see a virtual type as an internal formal generic
parameter or as a redefinable *typedef*.
Virtual type is a way to define in a class a property that is associated with a type.
This property can be used to type parameters, return of functions, variables, etc.
Virtual types are inherited by subclasses and can be redefined.

~~~
class Foo
type E: Object
var derp: E
Virtual types is a good solution when:

* A class need to refer to the real itself
* Two class hierarchy are somewhat parallel
* You want covariance

### Usage

Example, we have employees who work in standard office and bosses, that are technically employees, but they work in boss offices (that are improved offices with a fridge).

One way to model this is to use virtual types.
Virtual types are defined inside class (like methods and attributes) but with the keyword `type`.
Inside the class, the virtual type can be used (almost) like any other static type.

Subclasses can redefine (with `redef`) the virtual types they want to change.
The only requirement is that the new bound is a sub-type of the previous bound.

The redefinition of a virtual type is used by the compiler to prevent some type errors.
For example, assuming that boss' offices have a fridge:

~~~nitish
class Employee
type OFFICE: Office
var office: OFFICE
end
class Office
# ...
end
class Bar
super Foo
redef type E: Int
class Boss
super Employee
redef type OFFICE: BossOffice
end
class BossOffice
super Office
end
var b = new Bar(5)
print b.derp + 1 # outputs 6
var e: Employee = ...
e.office.fridge.open # Compilation Error! Office has no method fridge
var b: Boss = ...
b.office.fridge.open # OK!
~~~

0 comments on commit 0c45b71

Please sign in to comment.