State in Kew

The State feature in Kew provides access to state-related functions.

Creating, setting and retrieving state

To create a new state object (similar to a variable in many programming languages):

MyVariable: State new;

To set it:

MyVariable set 10;

To retrieve its value:

Output write (MyVariable get);

It’s a common error to forget to write get to retrieve the value. This results in you referring to the state object itself, which is often not what you want.

Passing state around

This scheme of having first-class stateful objects instead of built-in variables does have some advantages however. To pass state “by reference” (allowing another object to change it) is easy:

SomeObject: { modify Variable: Variable set 20; };

MyVariable: State new; MyVariable set 10;

SomeObject modify MyVariable; Output write (MyVariable get);

Instance variables

To create an “instance variable” for an object, you need to create state outside the scope of the object so its name is in scope for each method:

MyVariable: State new;

MyObject: { setValue Value: MyVariable set Value; writeLastValue: Output write (MyVariable get); };

MyObject setValue 10; MyObject writeLastValue;

Extending this idea a little, we can write an object factory instead:

SomeObjectFactory: { MyVariable: State new;

new: ^{
    setValue Value: MyVariable set Value;
    writeLastValue: Output write (MyVariable get);


This is a common pattern of use. Notice how in this case the scope within which MyVariable can be accessed is limited to the body of the factory object’s new method.

That covers the most elementary use of state in Kew but there are some more advanced features.