Wiki

root/cobra/trunk/Samples/Point.cobra

Revision 2019, 2.0 KB (checked in by Chuck.Esterbrook, 3 years ago)

Introduce .typeOf as a cross platform means of getting the type of an object.

  • Property svn:eol-style set to native
Line 
1"""
2Point.cobra
3
4This sample library class demonstrates numerous Cobra features including
5unit tests, contracts, properties, overrides, etc. in fairly small,
6easy-to-understand classes.
7
8You can run the test cases for this (and also test compile) like so:
9
10cobra -test Point.cobra
11
12Or build this into a Point.dll libary like so:
13
14cobra -t:lib -c Point.cobra
15
16Upon final delivery, you may wish to turn on optimizations while removing
17asserts, contracts and unit tests. You can do these individually or
18all in one fell swoop with the -turbo option:
19
20cobra -t:lib -turbo -c Point.cobra
21
22See cobra -h for more information.
23"""
24
25class Point
26    """
27    An immutable point in 2D space with integer coordinates.
28   
29    Because points are immutable they can be put in sets and used as keys in dictionaries.
30    """
31
32    test
33
34        p1 = Point(1, 2)
35        assert p1.x == 1 and p1.y == 2
36        assert p1.isPositive and not p1.isZero
37        assert p1.toString == 'Point(1, 2)'
38
39        p2 = p1.movedBy(3, 4)
40        assert p2.x == 4 and p2.y == 6
41        assert p1 <> p2
42       
43        p3 = Point(1, 2)
44        assert p1 == p3
45
46        assert Point.zero.isZero
47
48        points = {p1, p2, p3}  # a Set
49        # but p1 and p3 are not unique so:
50        assert points.count == 2
51        assert p1 in points and p2 in points and p3 in points
52
53    shared
54
55        var _zero = Point(0, 0)
56   
57        get zero as Point
58            """
59            Returns the zero point, (0, 0).
60            This is cached and slightly faster than creating a new point every time.
61            """
62            return _zero
63   
64    cue init(x as int, y as int)
65        ensure .x == x and .y == y
66        _x, _y = x, y
67   
68    get x from var as int
69   
70    get y from var as int
71   
72    get isPositive as bool
73        return .x > 0 and .y > 0
74
75    get isZero as bool
76        return .x == 0 and .y == 0
77
78    def movedBy(dx as int, dy as int) as Point
79        ensure result.x == .x+dx and result.y == .y+dy
80        return Point(_x+dx, _y+dy)
81
82    def toString as String is override
83        return '[.typeOf.name]([.x], [.y])'
84
85    def equals(other as Object?) as bool is override
86        if this is other, return true
87        if other inherits Point
88            return .x == other.x and .y == other.y
89        else
90            return false
91
92    def getHashCode as int is override
93        return .x ^ .y
Note: See TracBrowser for help on using the browser.