Understanding Smalltalk method syntax
This page introduces the syntax of methods and statements in Smalltalk.
You might first want to visit Understanding Pharo built-in data types, Understanding Smalltalk message syntax and Smalltalk method syntax on a postcard.
Methods are like code snippets, except that:
- They start with a declaration of the message and its parameters
- They must declare any temporary variables used
- They may explicitly return a value at the end of a block of statements with
^.
The example below shows the #lineCount method of the String
class. The first line declares the unary message lineCount without any parameters. This is followed by a comment (in double quotes), and the declaration of the lineCount variable (between or-bars).
The lineCount variable is then initialized, updated, and finally returned using the ^ return symbol.
String>>#lineCount
Smalltalk expressions consist of:
- A variable (e.g.,
lineCount)
- A literal (e.g.,
#lineCount; see Understanding Pharo built-in data types)
- A message send (e.g.,
lineCount+1; see Understanding Smalltalk message syntax)
Statements in Smalltalk consist of expressions separated by periods.
An
assignment
statement assigns the value of an expression to a variable using the built-in := operator. Note that this is
not
a message send.
A method can
return
the value of an expression with ^. If no return value is explicitly specified, a method returns self (the value of the receiver) when it ends.
All variables used in a method must be declared. Variables may be:
- formal parameters to the method (arguments)
- instance variables of the object (see A gentle introduction to classes and methods in Smalltalk)
- temporaries declared at the beginning of the method (e.g.,
| lineCount |)
- pseudo-variables (i.e.,
self,super,true,false,nil, orthisContext; see Understanding Pharo built-in data types)