doc/manual: put back the manual in the main repository
[nit.git] / doc / manual / genericity.md
1 # Generic Classes
2
3 Generic classes are defined with formal generic parameters
4 declared within brackets. Formal generic parameters can then be used as
5 a regular type inside the class. Generic classes must always be
6 qualified when used.
7
8 ~~~
9 class Pair[E]
10     var first: E
11     var second: E
12     fun is_same: Bool
13     do
14         return self.first == self.second
15     end
16 end
17 var p1 = new Pair[Int](1, 2)
18 print p1.second * 10 # outputs "20"
19 print p1.is_same # outputs "false"
20 var p2 = new Pair[String]("hello", "world")
21 p2.first = "world"
22 print p2.is_same # outputs "true"
23 ~~~
24
25 Unlike many object-oriented languages, generic classes in Nit yield a
26 kind of sub-typing. For example, `Pair[Int]` is a subtype of
27 `Pair[Object]`.