Understanding Smalltalk method syntax
TL;DR
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
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 ^
.
Example
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
Expressions
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
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.
Variables
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)