view 2-Io/day2-reflection.io @ 38:e8407d4e72dd

Add code on reflection - basically involves the object returned by "proto" message
author IBBoard <dev@ibboard.co.uk>
date Wed, 13 Sep 2017 20:11:52 +0100
parents
children
line wrap: on
line source

# Reflection in Io is about working out what goes on in slots
# We're now going to create an "ancestors" method that we needed
# on day 1 to find all slots!
Object ancestors := method(
    # Store our prototype
    prototype := self proto
    # If we're not at the top
    if (prototype != Object,
        # Then print the type name as a header
        writeln("Slots of ", prototype type,"\n--------------------")
        # And iterate the slots with foreach() before printing with writeln()
        # TODO: Find the difference between println and writeln, other than "message vs function"
        prototype slotNames foreach(slotName, writeln(slotName))
        # Blank line
        writeln
        # Recurse!
        prototype ancestors
    )
)

Animal := Object clone
Animal speak := method("*ambiguous animal noise" println)
Duck := Animal clone
Duck speak := method("Quack-quack!" println)
Duck walk := method("waddle" println)
donald := Duck clone
donald ancestors