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:
1. They start with a declaration of the message and its parameters
2. They must declare any temporary variables used
3. 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:
1. A
variable
(e.g., lineCount)
2. A
literal
(e.g., #lineCount; see Understanding Pharo built-in data types)
3. 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:
1. formal parameters to the method (arguments)
2. instance variables of the object (see A gentle introduction to classes and methods in Smalltalk)
3. temporaries declared at the beginning of the method (e.g., | lineCount |)
4. pseudo-variables (i.e., self, super, true, false, nil, or thisContext; see Understanding Pharo built-in data types)