Question: How do I dispatch the appropriate **iterator** for an subclassed
object?
The following is a simple exemplar to clarify: ( _in the real world where would
be many more subclass types_ )
We have two objects: ( **one** and **two** ) which are inherited from a common
class ( **Number** ) Both object types ( **Odd** and **Even** ) support a type
specific iterator ( **sample** )
Nim
import sequtils
type
Number = object of RootObj
Odd = object of Number
Even = object of Number
iterator sample(number: Number): int =
for i in [1, 2, 3]:
yield i
iterator sample(number: Odd): int =
for i in [1, 3, 5]:
yield i
iterator sample(number: Even): int =
for i in [0, 2, 4]:
yield i
var
number: Number
even: Even
odd: Odd
echo "Number: ", sample(number).toSeq
echo "Odd: ", sample(odd).toSeq
echo "Even: ", sample(even).toSeq
let list = [number, odd, even]
echo "\nList type: ", list.type
for item in list:
echo "----"
echo "Item type: ", item.type
if item of Number: echo "- Is a Number"
if item of Odd: echo "- Is an Odd"
if item of Even: echo "- Is an Even"
# FINALLY the question :-)
# - How do I dispatch the appropriate iterator for each item in the list?
# ( without hardcoding the dispatch )
#
# - Compiling with the following two lines not commented out gives:
# Error: undeclared field: 'sample' for type test.Number
# for item in list:
# echo item.sample
Run