Learn SMALLTALK with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
Smalltalk Counter and Theme Toggle
Object subclass: Counter [
| count isDark |
Counter class >> new [ ^ super new initialize ]
initialize [
count := 0.
isDark := false.
self updateUI.
]
updateUI [
Transcript show: 'Counter: ', count printString; cr.
Transcript show: 'Theme: ', (isDark ifTrue: ['Dark'] ifFalse: ['Light']); cr.
]
increment [ count := count + 1. self updateUI ]
decrement [ count := count - 1. self updateUI ]
reset [ count := 0. self updateUI ]
toggleTheme [ isDark := isDark not. self updateUI ]
]
| counter |
counter := Counter new.
counter increment.
counter increment.
counter toggleTheme.
counter decrement.
counter reset.
Demonstrates a simple counter with theme toggling using Smalltalk objects and messages.
2
Smalltalk Simple Addition
a := 10.
b := 20.
sum := a + b.
Transcript show: 'Sum: ', sum printString; cr.
Adds two numbers and prints the result.
3
Smalltalk Factorial
factorial := [:n | n <= 1 ifTrue: [1] ifFalse: [n * (factorial value: n-1)]].
Transcript show: 'Factorial 5: ', (factorial value: 5) printString; cr.
Calculates factorial recursively.
4
Smalltalk Fibonacci Sequence
fib := [:n | n < 2 ifTrue: [n] ifFalse: [(fib value: n-1) + (fib value: n-2)]].
1 to: 10 do: [:i | Transcript show: (fib value: i); cr].
Generates first 10 Fibonacci numbers.
5
Smalltalk Max of Two Numbers
a := 10.
b := 20.
max := a > b ifTrue: [a] ifFalse: [b].
Transcript show: 'Max: ', max printString; cr.
Finds the maximum of two numbers.
6
Smalltalk Array Sum
arr := #(1 2 3 4 5).
sum := 0.
arr do: [:x | sum := sum + x].
Transcript show: 'Sum: ', sum printString; cr.
Sums elements of an array.
7
Smalltalk Even Numbers Filter
arr := #(1 2 3 4 5).
arr do: [:x | (x \ 2 = 0) ifTrue: [Transcript show: x printString; cr]].
Prints even numbers from an array.
8
Smalltalk Conditional Counter Increment
count := 3.
(count < 5) ifTrue: [count := count + 1].
Transcript show: 'Count: ', count printString; cr.
Increment counter only if less than 5.
9
Smalltalk Resettable Counter
count := 0.
count := count + 1.
count := count + 1.
Transcript show: 'Count: ', count printString; cr.
count := 0.
Transcript show: 'Count: ', count printString; cr.
Counter that increments and can be reset.
10
Smalltalk Theme Toggle Only
isDark := false.
Transcript show: 'Theme: ', (isDark ifTrue: ['Dark'] ifFalse: ['Light']); cr.
isDark := isDark not.
Transcript show: 'Theme: ', (isDark ifTrue: ['Dark'] ifFalse: ['Light']); cr.
isDark := isDark not.
Transcript show: 'Theme: ', (isDark ifTrue: ['Dark'] ifFalse: ['Light']); cr.
Toggles theme multiple times.