Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Virtual type documentation with updated version. #2841

Merged
merged 1 commit into from
Aug 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!
~~~
Loading