"""
ImplementIEnumerable1.cobra
Implementing the IEnumerable interface allows an object to be used in a `for`
loop such as:
for record in fileCabinet
print record
and to be passed wherever an IEnumerable is expected such as the List
initializer:
records = List<of Record>(fileCabinet)
See also: ImplementIEnumerable1.cobra
"""
class FileCabinet
implements IEnumerable<of Record>
var _records = List<of Record>()
def newRecord(name as String) as Record
r = Record(_records.count+1, name)
_records.add(r)
return r
def getEnumerator as IEnumerator<of Record>
return _records.getEnumerator
def getEnumerator as System.Collections.IEnumerator
implements System.Collections.IEnumerable
return .getEnumerator
class Record
var _serialNum as int
var _name as String
def init(serialNum as int, name as String)
_serialNum = serialNum
_name = name
pro serialNum from var
pro name from var
def toString as String is override
return '[.getType.name]([_serialNum], [_name])'
class Program
def main is shared
# build a cabinet:
cabinet = FileCabinet()
cabinet.newRecord('Red')
cabinet.newRecord('Blue')
cabinet.newRecord('Green')
# because cabinet is an IEnumerable, it can be for'ed:
for record in cabinet
print record
# and passed to a List initializer:
records = List<of Record>(cabinet)
for record in records
assert record.serialNum > 0 |