Search code examples
oopsmalltalkpharosqueak

How to create a method using the Playground/Workspace (and not through the System Browser)?


I am learning Smalltalk using Pharo+Squeak. I try to use the Playground/Workspace as a console, and figure out how to do everything there. One thing I have not figured out yet is how to add a method to a class.

Let's say I create a Cat class

Object subclass: #Cat
    instanceVariableNames: ''
    classVariableNames: ''
    package: 'User Defined'.

To add a method makeSound to Cat, I can find it in the System Browser

Cat browse.

and create a new makeSound method there

makeSound
    "Make Cat object make sound."
    Transcript show: 'Meow!'.

I can then instantiate Cat and send it a makeSound message

cat := Cat new.
cat makeSound.

and it Meow! will show on the Transcript stream as expected.

Now, I do not know how to do all of this using the "console". In the Pharo by Example book it is mentioned that the convention for referring to methods is using ClassName>>methodName, and there are code snippets that look like this (I am probably butchering it!)

Cat class>>makeSound
  Transcript show: 'Meow!'.

It does not work when I type it in the Playground/Workspace.


Solution

  • This syntax is mostly used to insert methods into documents. It is not something that can be executed directly in the System Browser or in the Playground. For example take your method:

    Cat>>makeSound
        Transcript show: 'Meow!'.
    

    This just tells the reader that the method makeSound is in the class Cat. It's not executable. And it should be Cat>>makeSound and not Cat class>>makeSound. The second indicates that the method is on the class side.

    You can add a method to a class from the Workspace by compiling it:

    Cat 
      compile: 'makeSound
        "Make Cat object make sound."
        Transcript show: ''Meow!''.'
      classified: 'actions'.
    

    You can also directly access the compiled method object from a class using the message>>: Cat>>#makeSound. Once you have this method object you can also execute it on an object:

    (Cat>>#makeSound) valueWithReceiver: Cat new arguments: #().