Understanding Smalltalk method syntax
This page introduces the syntax of methods and statements in Smalltalk.
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
a value at the end of a block of statements with
The example below shows the
#lineCount method of the
ArrayedCollection subclass: #String
classVariableNames: 'AsciiOrder CSLineEnders CSNonSeparators CSSeparators CaseInsensitiveOrder CaseSensitiveOrder LowercasingTable Tokenish TypeTable UppercasingTable'
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).
lineCount variable is then initialized, updated, and finally returned using the
^ return symbol.
"Answer the number of lines represented by the receiver, where every line delimiter CR, LF or CRLF pair adds one line."
| lineCount |
lineCount := 0.
self lineIndicesDo: [:start :endWithoutDelimiters :end |
lineCount := lineCount + 1].
Smalltalk expressions consist of:
#lineCount; see Understanding Pharo built-in data types)
lineCount+1; see Understanding Smalltalk message syntax)
Statements in Smalltalk consist of expressions separated by periods.
statement assigns the value of an expression to a variable using the built-in
:= operator. Note that this is
a message send.
A method can
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.,
thisContext; see Understanding Pharo built-in data types)