Search code examples
methodscallsmalltalksqueak

How can I call a method in Squeak?


I am investigating Squeak Smalltalk. Somehow I defined an object that initializes and prints the initial value (the instructions for that were in homework). Then I had to define a method (getName), which I did, but I don't know what to do to call the method in the workspace.

To test initialization i used

a := Animal new.
Transcript show: a; cr.

But for anything more than that I just don't know what to do. I tried a getName and a.getName, and more. What is the right way?

Please, help! I don't even know what to Google.


Solution

  • In Smalltalk, you send a message to a receiver.

    e.g.
    Animal new sends the new message to Class Animal.
    This is an example of a unary message.

    Transcript show: a sends the show: message to Class Transcript, with an argument of a.
    This is an example of a keyword message.

    Transcript cr sends the message cr to Class Transcript.
    This is another example of a unary message.

    Transcript show: a ; cr .
    This is an example of a message cascade, where several messages in a row are sent to the same receiver.

    In a message cascade, you only type the name of the receiver once, use ; to separate the remainders of each message.

    Transcript show: a ; cr .

    In Smalltalk, keywords which have an argument must have a colon suffix.

    The convention is that simple accessors use the same name as the instance variable they access; and an instance of Class Object will have a variable name of the form anObject.

    So an instance variable named name would have a getter called name and a setter called name:

    Conventionally, we'd then have:

    anAnimal := Animal new.
    Transcript show: anAnimal name ;
               cr .
    

    Here, we send the name message to anAnimal. It returns the name of anAnimal. As a unary message, it has higher precedence than the keyword message Transcript show: <something>, and so is evaluated first. The return from the anAnimal name message becomes the argument to the Transcript show: <something> message.

    You can see this for yourself. In the Workspace, highlight anAnimal name and then click and choose 'Inspect it'. This will bring up an Inspector window, and it will show you the object returned by the anAnimal name message.

    These answers may help you understand:
    Explain a piece of Smalltalk code
    Keyword messages in smalltalk

    This article, Beginning to Smalltalk: Hello World, goes into it in a little more detail, using Transcript show: 'Hello World'.