Write, Run & Share Smalltalk code online using OneCompiler's Smalltalk online editor for free. It's one of the robust, feature-rich online editors for Smalltalk. Getting started with the OneCompiler's Smalltalk online editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'Smalltalk' and start writing code to learn and test online without worrying about tedious process of installation.
Smalltalk is a pioneering object-oriented programming language created at Xerox PARC in the 1970s. Everything in Smalltalk is an object, including numbers, characters, and even code blocks. The language influenced many modern languages like Ruby, Python, and Objective-C. Smalltalk uses message passing as its fundamental mechanism for computation.
Smalltalk syntax is simple and consistent - you send messages to objects. Statements end with periods, and the caret ^ returns values from methods. Comments are enclosed in double quotes. Variable assignments use := and local variables are declared between pipe symbols |var1 var2|.
"This is a comment"
"Print to transcript"
Transcript show: 'Hello, World!'.
Transcript show: 'Hello'; cr. "cr adds newline"
"Variable assignment"
| x y sum |
x := 10.
y := 20.
sum := x + y.
Transcript show: sum printString.
"Return value (caret)"
^ sum
Everything in Smalltalk is an object that responds to messages. There are three types of messages: unary (no arguments), binary (one argument, operator-like), and keyword (named arguments with colons). Messages are evaluated left to right, with unary first, then binary, then keyword.
"Unary messages (no arguments)"
5 negated. "Returns -5"
'hello' size. "Returns 5"
3.14 rounded. "Returns 3"
true not. "Returns false"
"Binary messages (operators)"
3 + 4. "Returns 7"
10 - 5. "Returns 5"
6 * 7. "Returns 42"
20 / 4. "Returns 5"
10 // 3. "Integer division: 3"
10 \\ 3. "Modulo: 1"
5 = 5. "Equality: true"
5 < 10. "Comparison: true"
"Keyword messages (named arguments)"
'hello' at: 1. "Returns $h"
'hello' copyFrom: 1 to: 3. "Returns 'hel'"
10 between: 1 and: 20. "Returns true"
5 max: 10. "Returns 10"
"Message chaining (cascading with semicolon)"
Transcript show: 'Hello'; cr; show: 'World'; cr.
Smalltalk has a rich numeric hierarchy including integers, floats, fractions, and large integers with automatic precision. Arithmetic operations are messages sent to number objects. Fractions are first-class objects that maintain exact precision.
"Integer operations"
| a b |
a := 42.
b := 7.
Transcript show: (a + b) printString; cr.
Transcript show: (a * b) printString; cr.
Transcript show: (a // b) printString; cr. "Integer division"
Transcript show: (a \\ b) printString; cr. "Modulo"
"Floats"
3.14159 rounded. "3"
3.7 floor. "3"
3.2 ceiling. "4"
2.5 truncated. "2"
"Fractions (exact arithmetic)"
(1/3) + (1/6). "Returns 1/2"
(2/3) * (3/4). "Returns 1/2"
"Math functions"
16 sqrt. "4.0"
2 raisedTo: 10. "1024"
100 log. "2.0 (base 10)"
2.718 ln. "~1.0 (natural log)"
(-5) abs. "5"
Strings are sequences of characters enclosed in single quotes. Characters are prefixed with a dollar sign. Strings are collections, so you can iterate over them and use collection methods. String concatenation uses the comma operator.
"String basics"
| str |
str := 'Hello, World!'.
Transcript show: str; cr.
Transcript show: str size printString; cr. "13"
"Character (prefix with $)"
$a. "Character a"
$a asciiValue. "97"
65 asCharacter. "$A"
"String operations"
'Hello', ' World'. "Concatenation: 'Hello World'"
'hello' asUppercase. "HELLO"
'HELLO' asLowercase. "hello"
'hello' reversed. "olleh"
'hello' at: 1. "$h"
'hello' first. "$h"
'hello' last. "$o"
'hello world' substrings. "#('hello' 'world')"
"String testing"
'hello' includes: $e. "true"
'hello' beginsWith: 'hel'. "true"
'hello' endsWith: 'lo'. "true"
'' isEmpty. "true"
"String formatting"
'Value: ', 42 printString. "'Value: 42'"
Smalltalk has powerful collection classes including Arrays, OrderedCollections (dynamic arrays), Sets, and Dictionaries. Collections support iteration, filtering, and transformation through blocks. The #(...) syntax creates literal arrays.
"Array (fixed size)"
| arr |
arr := #(1 2 3 4 5). "Literal array"
arr := Array new: 5. "Empty array of size 5"
arr at: 1 put: 10. "Set element"
arr at: 1. "Get element: 10"
"OrderedCollection (dynamic)"
| list |
list := OrderedCollection new.
list add: 'first'.
list add: 'second'.
list addFirst: 'zero'.
list removeLast.
list size. "2"
"Set (unique elements)"
| set |
set := Set new.
set add: 1; add: 2; add: 1. "Contains only 1 and 2"
set includes: 1. "true"
"Dictionary (key-value pairs)"
| dict |
dict := Dictionary new.
dict at: 'name' put: 'John'.
dict at: 'age' put: 30.
dict at: 'name'. "'John'"
dict keys. "Set of keys"
dict values. "Collection of values"
"Collection iteration"
#(1 2 3 4 5) do: [:each | Transcript show: each printString; cr].
#(1 2 3) collect: [:x | x * 2]. "#(2 4 6)"
#(1 2 3 4 5) select: [:x | x > 2]. "#(3 4 5)"
#(1 2 3 4 5) reject: [:x | x > 2]. "#(1 2)"
#(1 2 3 4 5) detect: [:x | x > 3]. "4"
#(1 2 3 4 5) inject: 0 into: [:sum :x | sum + x]. "15"
Blocks are anonymous functions enclosed in square brackets. They are first-class objects that can be stored, passed, and executed. Blocks are used for control flow, iteration, and callbacks. Parameters are declared with colons at the start.
"Block basics"
| block |
block := [Transcript show: 'Hello'].
block value. "Execute block"
"Block with parameters"
| add |
add := [:a :b | a + b].
add value: 3 value: 4. "7"
"Block with local variables"
[:x | | temp | temp := x * 2. temp + 1] value: 5. "11"
"Conditionals"
| x |
x := 10.
x > 5 ifTrue: [Transcript show: 'Big'].
x > 5 ifFalse: [Transcript show: 'Small'].
x > 5 ifTrue: [Transcript show: 'Big'] ifFalse: [Transcript show: 'Small'].
"While loops"
| i |
i := 1.
[i <= 5] whileTrue: [
Transcript show: i printString; cr.
i := i + 1
].
"Times repeat"
5 timesRepeat: [Transcript show: 'Hello'; cr].
"To do (for loop)"
1 to: 5 do: [:i | Transcript show: i printString; cr].
1 to: 10 by: 2 do: [:i | Transcript show: i printString; cr]. "1,3,5,7,9"
Smalltalk is purely object-oriented - everything is an object, and all computation happens through message passing. Classes define the structure and behavior of objects. Instance variables hold state, and methods define behavior.
"Define a class (conceptual - syntax varies by implementation)"
Object subclass: #Person
instanceVariableNames: 'name age'
classVariableNames: ''
package: 'MyPackage'.
"Instance method"
Person >> initialize
name := 'Unknown'.
age := 0.
Person >> name
^ name.
Person >> name: aName
name := aName.
Person >> age
^ age.
Person >> age: anAge
age := anAge.
Person >> greet
^ 'Hello, I am ', name, ' and I am ', age printString, ' years old.'.
"Using the class"
| person |
person := Person new.
person name: 'John'.
person age: 30.
Transcript show: person greet; cr.
"Class method"
Person class >> createWithName: aName age: anAge
^ self new name: aName; age: anAge; yourself.
"Usage"
person := Person createWithName: 'Jane' age: 25.
Smalltalk uses exceptions for error handling with on:do: blocks. You can signal errors and define handlers for specific exception types. The exception hierarchy allows catching broad or specific error categories.
"Basic exception handling"
[
"Code that might fail"
1 / 0
] on: Error do: [:ex |
Transcript show: 'Error: ', ex messageText; cr
].
"Signaling errors"
Error signal: 'Something went wrong'.
"Multiple exception types"
[
"Risky code"
] on: ZeroDivide do: [:ex |
Transcript show: 'Division by zero!'; cr
] on: Error do: [:ex |
Transcript show: 'Other error: ', ex messageText; cr
].
"Ensure (finally equivalent)"
[
"Code that might fail"
] ensure: [
"Always executed (cleanup)"
Transcript show: 'Cleanup done'; cr
].
"ifCurtailed (only on error)"
[
"Code that might fail"
] ifCurtailed: [
"Only executed if error occurs"
].
Smalltalk has idiomatic patterns for common operations. The cascade operator (;) sends multiple messages to the same receiver. The yourself message returns the receiver, useful in cascades that end with a setter.
"Cascade - multiple messages to same object"
| list |
list := OrderedCollection new
add: 1;
add: 2;
add: 3;
yourself. "Returns the collection, not last add result"
"Copying"
| original copy |
original := #(1 2 3).
copy := original copy. "Shallow copy"
copy := original deepCopy. "Deep copy"
"Testing object types"
5 isInteger. "true"
3.14 isFloat. "true"
'hello' isString. "true"
#(1 2 3) isArray. "true"
nil isNil. "true"
5 isKindOf: Number. "true"
5 isMemberOf: SmallInteger. "true"
"Identity vs equality"
a = b. "Equality (value)"
a == b. "Identity (same object)"
"Printing and debugging"
object printString. "String representation"
object inspect. "Open inspector"
object halt. "Breakpoint"