Wiki

root/cobra/trunk/HowTo/300-ImplementIEnumerable1.cobra

Revision 2127, 1.3 KB (checked in by Chuck.Esterbrook, 3 years ago)

Take out is shared on def main in the how-to's.

  • Property svn:eol-style set to native
Line 
1"""
2ImplementIEnumerable1.cobra
3
4Implementing the IEnumerable interface allows an object to be used in a `for`
5loop such as:
6
7    for record in fileCabinet
8        print record
9
10and to be passed wherever an IEnumerable is expected such as the List
11initializer:
12
13    records = List<of Record>(fileCabinet)
14
15
16See also: ImplementIEnumerable1.cobra
17"""
18
19
20class FileCabinet implements IEnumerable<of Record>
21
22    var _records = List<of Record>()
23
24    def newRecord(name as String) as Record
25        r = Record(_records.count+1, name)
26        _records.add(r)
27        return r
28
29    def getEnumerator as IEnumerator<of Record>
30        return _records.getEnumerator
31
32    def getEnumerator as System.Collections.IEnumerator
33        implements System.Collections.IEnumerable
34        return .getEnumerator
35
36
37class Record
38
39    cue init(serialNum as int, name as String)
40        base.init
41        _serialNum, _name = serialNum, name
42
43    pro serialNum from var as int
44
45    pro name from var as String
46
47    def toString as String is override
48        return '[.typeOf.name]([_serialNum], [_name])'
49
50
51class Program
52
53    def main
54        # build a cabinet:
55        cabinet = FileCabinet()
56        cabinet.newRecord('Red')
57        cabinet.newRecord('Blue')
58        cabinet.newRecord('Green')
59
60        # because cabinet is an IEnumerable, it can be for'ed:
61        for record in cabinet
62            print record
63
64        # and passed to a List initializer:
65        records = List<of Record>(cabinet)
66        for record in records
67            assert record.serialNum > 0
Note: See TracBrowser for help on using the browser.