Version 2 of oo::configurable

Updated 2023-05-21 17:24:07 by dkf

The oo::configurable class is a part of TclOO in Tcl 8.7. It is a metaclass, i.e., it modifies how you create classes, adding the capability to define properties on the class. It also modifies the class to add a configure method (via a mixin). The configure method is aware of the properties defined across the inheritance hierarchy for the class.

Examples

In particular, this means that if one does:

oo::configurable create Point {
    property x y
    constructor args {
        my configure -x 0 -y 0 {*}$args
    }
    variable x y
    method print {} {
        puts "x=$x, y=$y"
    }
}

You can then do:

set pt [Point new -x 27]
$pt print;   # x=27, y=0
$pt configure -y 42
$pt print;   # x=27, y=42
puts "distance from origin: [expr {
    hypot([$pt configure -x], [$pt configure -y])
}]";         # distance from origin: 49.92995093127971
puts [$pt configure]
             # -x 27 -y 42

That can then be extended with more properties by a subclass:

oo::configurable create Point3D {
    superclass Point
    property z
    constructor args {
        next -z 0 {*}$args
    }
}

set pt2 [Point3D new -x 2 -y 3 -z 4]
puts [$pt2 configure]
              # -x 2 -y 3 -z 4