From 41dba0476bc6824d201ede224fed5b2f51c80497 Mon Sep 17 00:00:00 2001 From: Hugo Leblanc Date: Wed, 17 Jul 2024 13:33:16 -0400 Subject: [PATCH] Update virtual_type.md This takes the better manual documentation from the nit website. Signed-off-by: Hugo Leblanc --- doc/manual/virtual_type.md | 56 ++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/doc/manual/virtual_type.md b/doc/manual/virtual_type.md index 042c721831..64c38d6b96 100644 --- a/doc/manual/virtual_type.md +++ b/doc/manual/virtual_type.md @@ -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! ~~~