Ets

Inherits from Object

Ets — in-memory key/value table, shared between actors or private to one.

Ets is not a Collection, but it uses: Enumerable(V): iteration and query methods (do:, select:, collect:, inject:into:, …) run over a snapshot of the values. size, isEmpty and isNotEmpty are answered directly from the table without copying it.

Wraps OTP ets tables with a Beamtalk-friendly API.

ETS tables are owned by the creating process. When the owner terminates, the table is deleted automatically unless an heir is configured.

Constructors

ConstructorNameWho may read / writeUse for
new:type:globalany process / any processState shared between actors
newOrExisting:type:globalany process / any processShared state that may already exist
private:noneowner only / owner onlyOne actor's internal state, secrets
protected:noneany process / owner onlyOne writer, many concurrent readers

A named table's name is global to the node, so two instances of the same actor cannot each create #cache. Unnamed tables have no such clash: make one per actor in initialize and keep it in a field typed :: Ets. They are reached only through the Ets value, never by named:.

Missing keys

at: answers nil for an absent key (its type is V | Nil). This differs from Dictionary at:, which raises key_error, on purpose: an Ets table is shared mutable state, so the key can vanish between a check and a read, and the V | Nil type makes the caller handle the miss. A stored nil is indistinguishable from an absent key with at:; use at:ifPresent:ifAbsent: (which treats a stored nil as present) to tell them apart.

Using an unnamed table from a process its protection forbids raises access_denied. A private table's contents are also hidden from other processes' inspection, and printing an Ets never shows its contents.

Table Types

SymbolDescription
#setOne entry per key (default, unordered)
#orderedSetOne entry per key, keys sorted
#bagMultiple entries per key, values must differ
#duplicateBagMultiple identical entries per key allowed

Examples

cache := Ets new: #myCache type: #set
cache at: "key" put: 42
cache at: "key"                        // => 42
cache at: "missing"                    // => nil
cache at: "missing" ifAbsent: [0]      // => 0
cache includesKey: "key"               // => true
cache size                             // => 1
cache removeKey: "key"
cache delete

Cross-Actor Sharing

cache := Ets new: #sharedCache type: #set
// In another actor — retrieve by name:
shared := Ets named: #sharedCache
shared at: "counter" put: 1

Actor-Internal State

Actor subclass: SessionStore
  state: table :: Ets
  initialize -> Nil =>
    self.table := Ets private: #set
    nil
  remember: id state: s => self.table at: id put: s
  claim: id => self.table removeKey: id ifAbsent: [nil]

Class Methods

new: name type: tableType Sealed source

Create a new named public ETS table (class method).

tableType must be one of: #set, #orderedSet, #bag, #duplicateBag. The table is created as named_table with public access so that any process can read and write it. Raises already_exists if a table with the same name already exists.

Examples

cache := Ets new: #myCache type: #set
counters := Ets new: #counters type: #set
private: tableType Sealed source

Create an unnamed, private ETS table owned by the caller (class method).

Only the creating process may read or write it; any other process gets access_denied. There is no node-global name, so every caller (for example each instance of an actor) gets its own table and no atom is created. The table is deleted when its owner terminates. Use it for an actor's internal state, especially secrets such as tokens or nonces.

The owner is the process that runs this call: create the table in the long-lived actor that will use it (e.g. in initialize). Each REPL input runs in a short-lived process, so a table created at the REPL is deleted when that input finishes. A process-bound class method (new, spawn, ...) runs in the class's process, so a table made there belongs to that process and callers get access_denied.

Examples

// Both lines must run in the same process (one REPL input or one method body).
secrets := Ets private: #set
secrets at: "nonce" put: "abc"
protected: tableType Sealed source

Create an unnamed, protected ETS table owned by the caller (class method).

Any process holding the Ets may read it, but only the creating process may write; a write from another process raises access_denied. The table is deleted when its owner terminates.

Examples

published := Ets protected: #set
named: name Sealed source

Look up an existing named ETS table (class method).

Returns an Ets instance if a table with the given name exists. Raises not_found if no table with that name has been created.

Examples

cache := Ets named: #myCache
exists: name Sealed source

Check whether a named ETS table exists.

Returns true if a table with the given name exists, false otherwise.

Examples

Ets exists: #myCache    // => false
Ets new: #myCache type: #set
Ets exists: #myCache    // => true
newOrExisting: name type: tableType Sealed source

Create a named table or return the existing one.

If a table with the given name already exists, returns an Ets instance wrapping it. Otherwise creates a new table with the specified type. This is useful in setUp/tearDown cycles where the previous owner may still be alive.

Examples

table := Ets newOrExisting: #events type: #set

Instance Methods

at: key source

Look up a key. Returns the value, or nil if the key is absent.

For #bag and #duplicateBag tables with multiple entries per key, returns the first stored value. The current wrapper exposes only one value per key; bag tables are best suited for single-value-per-key use.

Examples

cache at: "key"        // => value or nil
at: key put: value source

Insert or replace a key-value pair. Returns nil.

For #bag and #duplicateBag tables, all existing entries for key are removed before the new entry is inserted, giving best-effort upsert semantics. Concurrent writes from multiple actors to the same key on a bag table are not serialized — interleaved operations may result in multiple entries for that key.

Examples

cache at: "counter" put: 1
at: key ifAbsent: block source

Look up a key; if absent, evaluate the block and return its result.

For #bag and #duplicateBag tables with multiple entries per key, returns the first stored value (same as at:); the block is not called.

Examples

cache at: "missing" ifAbsent: [0]    // => 0
cache at: "key"     ifAbsent: [0]    // => stored value
at: key ifPresent: block source

Look up a key; if present, evaluate the block with the value and answer its result, otherwise answer nil.

Works on every table type; for #bag and #duplicateBag the block receives the first stored value (same as at:).

Examples

cache at: "n" put: 2
cache at: "n" ifPresent: [:v | v * 10]    // => 20
cache at: "zz" ifPresent: [:v | v * 10]   // => nil
at: key ifPresent: presentBlock ifAbsent: absentBlock source

Look up a key; evaluate presentBlock with the value if present, or absentBlock if absent, and answer the result.

A stored nil is present: presentBlock runs with nil. One table lookup decides the branch, so the answer is consistent even if another process changes the table concurrently. Same as Dictionary at:ifPresent:ifAbsent:.

Examples

cache at: "n" put: 2
cache at: "n" ifPresent: [:v | v * 10] ifAbsent: [0]    // => 20
cache at: "zz" ifPresent: [:v | v * 10] ifAbsent: [0]   // => 0
at: key increment: n source

Atomically add n to the Integer stored at key and answer the new value. A missing key starts at 0, so this creates it.

Backed by ets:update_counter/4, so concurrent callers never lose an update. Supported on #set and #orderedSet only; #bag and #duplicateBag raise unsupported_table_type. A non-Integer n or a non-Integer stored value raises type_error.

Examples

counters at: "hits" increment: 1    // => 1
counters at: "hits" increment: 5    // => 6
at: key update: block source

Atomic read-modify-write. Evaluates block with the current value (nil if the key is missing), stores the block's result and answers it.

Implemented as an optimistic compare-and-swap loop: if another process changes the key meanwhile, the block is re-run with the new value. So the block must be free of side effects — it may run more than once. A block that raises propagates the error and writes nothing. Retries are bounded; exhaustion raises update_contention. Supported on #set and #orderedSet only; #bag and #duplicateBag raise unsupported_table_type. Unlike the other at: selectors, keys that are or contain a Dictionary, #_ or a #$N symbol raise type_error (they cannot be matched exactly by the compare-and-swap).

Examples

cache at: "list" update: [:old | old isNil ifTrue: [#(1)] ifFalse: [old , #(2)]]
includesKey: key source

Return true if the table contains an entry for key.

Examples

cache includesKey: "key"    // => true or false
removeKey: key source

Remove the entry for key. Returns nil. Idempotent if key is absent.

Examples

cache removeKey: "oldKey"
removeKey: key ifAbsent: block source

Atomically remove the entry for key and answer its value; if key is absent, evaluate block and answer its result.

Backed by ets:take/2: no other process can read or take the value in between, so this suits single-use values such as one-time tokens. For #bag and #duplicateBag every entry for key is removed and the first stored value is answered.

Examples

cache at: "token" put: 7
cache removeKey: "token" ifAbsent: [nil]    // => 7
cache removeKey: "token" ifAbsent: [nil]    // => nil
keys source

Return all keys in the table as a List.

Order is unspecified for #set and #bag tables. Keys are sorted for #orderedSet tables. For #bag and #duplicateBag tables, each key appears only once.

Examples

cache keys    // => #("key1", "key2")
values source

Return all values as a List (a point-in-time read).

Order is unspecified for #set, #bag, #duplicateBag; key order for #orderedSet. Bag tables yield one value per stored entry.

Examples

cache values    // => #(1, 2)
elements source

The values as a List snapshot — the one method Enumerable requires. Gives Ets do:, inject:into:, select:, reject:, collect:, detect:, detect:ifNone:, anySatisfy:, allSatisfy:, noneSatisfy:, includes: (values, not keys; includesKey: is the key test) and count: over a point-in-time copy of the values.

keysAndValuesDo: block source

Evaluate block with each key and value of a snapshot taken up front (the block may modify the table). Returns nil.

Examples

cache keysAndValuesDo: [:k :v | Transcript show: k]
doWithKey: block source

Evaluate block with each key and value of a snapshot, as Dictionary doWithKey: does. Same as keysAndValuesDo:.

Examples

cache doWithKey: [:k :v | Transcript show: k]
asDictionary source

Take a point-in-time snapshot as an immutable Dictionary.

For #bag and #duplicateBag tables, only one value per key survives: the last one read, whereas at: answers the first.

Examples

cache asDictionary    // => #{"a" => 1}
isEmpty source

Return true if the table has no entries.

Examples

cache isEmpty    // => true
isNotEmpty source

Return true if the table has at least one entry.

Examples

cache isNotEmpty    // => false
includes: value source

Return true if any entry holds value. Scans a snapshot of the values.

Examples

cache includes: 42    // => true or false
removeAll source

Remove every entry but keep the table. Returns nil.

Examples

cache removeAll
size source

Return the number of entries in the table.

Examples

cache size    // => 3
delete source

Destroy the table, freeing all memory. Returns nil.

Any process may delete a named (public) table. Only the process that created a private:/protected: table (the owner) may delete it; any other process raises access_denied. Deleting a table that is already gone raises stale_table, for named and unnamed tables alike. After calling delete, this Ets instance is no longer valid. Any further operations on the deleted table will raise an error.

Examples

cache delete

Inherited Methods

From Object

class

Return the class of the receiver.

Examples

42 class              // => Integer
"hello" class         // => String
isNil

Test if the receiver is nil. Returns false for all objects except nil.

Examples

42 isNil              // => false
nil isNil             // => true
notNil

Test if the receiver is not nil. Returns true for all objects except nil.

Examples

42 notNil             // => true
nil notNil            // => false
ifNil: _nilBlock

If the receiver is nil, evaluate nilBlock. Otherwise return self.

_nilBlock is never evaluated on this Object-level definition (only UndefinedObject's override calls it, with Block(R) -> R), so R is unconstrained here — parameterizing it still documents the zero-arg shape without implying this branch produces R (BT-2834).

Examples

42 ifNil: [0]         // => 42
nil ifNil: [0]        // => 0
ifNotNil: notNilBlock

If the receiver is not nil, evaluate notNilBlock with self.

Left as a bare Block deliberately (BT-2834): notNilBlock is invoked one-arg with self and its result becomes the method's own result, so a precise signature needs a Self-in-Block(...) type-arg form (Block(Self, R) -> R) with no precedent elsewhere in stdlib. The type checker doesn't consult this declared signature for ifNotNil: anyway — it narrows the block's parameter from the receiver's own type via infer_args_for_if_not_nil in inference.rs (BT-2046), independent of this stdlib declaration.

Examples

42 ifNotNil: [:v | v + 1]   // => 43
nil ifNotNil: [:v | v + 1]  // => nil
ifNil: _nilBlock ifNotNil: notNilBlock

If nil, evaluate nilBlock; otherwise evaluate notNilBlock with self.

Bare Block params here (unlike UndefinedObject's Block(R) -> R override, BT-2824) are intentional, not an oversight: the type checker never consults this declared signature for these two selectors — it reads the block arguments' actual inferred return types directly (if_nil_branch_union_ret_ty in inference.rs, BT-2047) since a bare -> R here can't express "whatever the block returns" without a Self-in-Block(...) type-arg form with no precedent elsewhere in stdlib.

Examples

42 ifNil: [0] ifNotNil: [:v | v + 1]    // => 43
nil ifNil: [0] ifNotNil: [:v | v + 1]   // => 0
ifNotNil: notNilBlock ifNil: _nilBlock

If not nil, evaluate notNilBlock with self; otherwise evaluate nilBlock.

See ifNil:ifNotNil: above — the bare Block params are intentional.

Examples

42 ifNotNil: [:v | v + 1] ifNil: [0]    // => 43
nil ifNotNil: [:v | v + 1] ifNil: [0]   // => 0
then: aBlock

Answer the result of evaluating aBlock with the receiver (ADR 0145 § 2, named after Elixir's Kernel.then/2).

The escape hatch for putting a value somewhere other than the receiver of the next message, typically after |>. It is an ordinary message, so it also works without |>. Put |> in front of a then: that follows a keyword message: without it, xs inject: 0 into: [...] then: [...] is one inject:into:then: send.

The aBlock param is deliberately untyped. Every class inherits this method, so a declared Block would make each user class's own then: with another parameter type (a parser combinator's then: next :: Parser, say) draw an override-incompatibility warning. The type checker does not consult this signature for a literal block anyway: it types the block's parameter as the receiver's type and answers the block's result type (infer_args_for_then in inference/blocks.rs, BT-4515).

then: is not inlined and not sealed. A class that defines its own then: (a promise, say) keeps it. Because it is a message, on an actor receiver the block runs in the actor's process, so a block that sends back to the calling actor (or, through TimeoutProxy, to the proxy) fails with deadlock_detected or a call timeout; on a class receiver it runs in the caller (ADR 0142). A block passed to it that assigns a captured local is an escaping block (ADR 0133), a compile error: bind the value to a temp local instead. TimeoutProxy forwards then: to its target, so the target's own then: runs if it has one.

Examples

3 then: [:x | x * x]                       // => 9
#(1, 2, 3) collect: [:x | x * 2] |> then: [:xs | xs size * 10]   // => 30
printString

Return the developer-readable (Debug) string representation.

printString is the Debug protocol (ADR 0094): the self-describing, structural form used by the REPL, logs, and by any other printString that nests this object. It is the REPL default — evaluating an expression shows its printString.

This default returns the bare class name (no a/an article — the old "a ClassName" form was dropped in ADR 0094). Value overrides it with the structural ClassName(field: value, ...) form, actors render as Actor(ClassName, pid), supervisors as Supervisor(ClassName, pid) / DynamicSupervisor(ClassName, pid), and primitive types (Integer, String, List, …) override it with their own richer output. Authors rarely override printString directly — the default is derived.

Examples

42 printString            // => "42"
displayString

Return the user-facing (Display) string representation.

displayString is the Display protocol (ADR 0094): the human-facing form. It is the hook the language pulls during string interpolation — every {...} segment renders via the value's displayString. Developers rarely call it directly; they override it when a value has a natural human rendering (e.g. Money → $10.50, where printString would still show the Debug form).

It defaults to printString, so most types need no override. String and Symbol demonstrate the split: "hi" printString → "\"hi\"" (quoted, Debug) while "hi" displayString → "hi" (plain, Display); likewise #foo drops its # prefix under displayString.

displayString is not part of the Printable protocol (deferred per ADR 0094 §5).

Examples

42 displayString             // => "42"
inspect

Open a navigable Inspector cursor on the receiver.

ADR 0095 Phase 3 (BT-2504). inspect is repurposed from -> String (the ADR-0094 deferral) to the verb that produces an Inspector — a live, immutable cursor for drilling into the object (Inspector on: self). anObject inspect is the shorthand; Inspector on: anObject is the explicit spelling. The cursor exposes fields/at:/path/refresh/ printString (an indented text tree) and asDictionaries (the MCP/browser wire form); see Inspector.

This is a breaking change: code that used inspect for its old String result must switch to printString (the structural Debug string, ADR 0094) — a transitional lint flags inspect used directly in ++/ string position.

Examples

42 inspect kind                  // => #value
(Point x: 3 y: 4) inspect fields size   // => 2
(Point x: 3 y: 4) printString    // => "Point(x: 3, y: 4)"  (the old inspect string)
yourself Sealed

Return the receiver itself. Useful for cascading side effects.

Examples

42 yourself            // => 42
hash

Return a hash value for the receiver.

Examples

42 hash
equals: other

Test value equality — the overridable counterpart to =:=.

Defaults to =:= (Erlang structural term equality), so for most classes the two agree. Unlike =:=, this is an ordinary message send, so a class whose logical value is not its representation can override it: a persistent structure whose shape depends on construction history, a timestamp that should compare by instant rather than by wall-clock fields, or a type with a normalising form. =:=, =/=, == and /= are lowered straight to Erlang BIFs (ADR 0002) and cannot be overridden — the compiler rejects any attempt (BT-2997).

What honours it

The linear scans: includes: on Collection, List, Array and Dictionary (which searches values), plus List>>indexOf: and TestCase>>assert:equals:.

Contract

An override must agree with =:= wherever =:= holds — a =:= b must imply a equals: b. It may only make more values equal, never fewer. The scans above rely on this: each tries raw =:= first and dispatches only on a miss, so a fast-path hit is always a genuine equals: hit.

Caveat

Set, Dictionary keys, and List>>unique decide identity in the VM with raw =:=, never through this method — keying and deduplication need an order or a hash that a user-defined equals: cannot supply. A class that overrides equals: still deduplicates by representation when used as a key or element. Normalise the representation if that matters.

Examples

42 equals: 42           // => true
42 equals: 42.0         // => false (defaults to strict `=:=`)
"ab" equals: "ab"       // => true
respondsTo: selector Sealed

Test if the receiver responds to the given selector.

Examples

42 respondsTo: #abs    // => true
fieldNames Sealed

Return the names of fields.

Examples

42 fieldNames             // => #()
fieldAt: name Sealed

Return the value of the named field.

Left without a declared return type deliberately (BT-2834 pattern, see Block>>value): the field's actual value can be any type, and callers routinely send it further messages ((self fieldAt: #x) + 1) that a fixed -> Object would statically reject.

Examples

object fieldAt: #name
fieldAt: name put: value Sealed

Set the value of the named field. Answers value.

Examples

object fieldAt: #name put: "Alice"
hasField: name Sealed

Test whether the receiver has the named field. Never raises — the non-raising counterpart to fieldAt:, in particular for a late slot (ADR 0124): fieldAt: raises UninitializedStateError reading an unassigned late slot, hasField: is the question to ask first.

Examples

c := CodexClient start: "/tmp/ws" config: cfg onEvent: nil
c hasField: #proc      // => false — declared `late`, not yet assigned
c launch
c hasField: #proc      // => true
42 hasField: #anything // => false — primitives have no fields
clearField: name Sealed

Return a late field to the unassigned state (ADR 0124), so it can be assigned again (e.g. re-acquiring a resource). Joins fieldAt:/ fieldAt:put:/fieldNames in ADR 0035's field-prefixed reflection family. Returns self.

Examples

c clearField: #proc
c hasField: #proc       // => false — relaunchable
perform: selector Sealed

Send a unary message dynamically.

Declared -> Dynamic explicitly (BT-4044): the invoked method's return type is unknown statically, so the reflective result really is unknown — and unlike the BT-2834 unannotated pattern (see fieldAt: above), an explicit Dynamic does not warn at call sites in typed classes. Chained sends on the result still check dynamically, as before.

Examples

42 perform: #abs       // => 42
perform: selector withArguments: args Sealed

Send a message dynamically with arguments.

See perform: above for why the return type is declared Dynamic.

Examples

3 perform: #max: withArguments: #(5)   // => 5
subclassResponsibility

Raise an error indicating this method must be overridden by a subclass.

Examples

self subclassResponsibility
notImplemented

Raise an error indicating this method has not yet been implemented.

Use this for work-in-progress stubs. Distinct from subclassResponsibility, which signals an interface contract violation.

Examples

self notImplemented
show: aValue

Send aValue to Transcript without a trailing newline.

Outside an interactive workspace this is a Logger notice (ADR 0129 §5).

Examples

42 show: "value: "
showCr: aValue

Send aValue to Transcript followed by a newline.

Outside an interactive workspace this is a Logger notice (ADR 0129 §5).

Examples

42 showCr: "hello world"
isKindOf: aClass

Test if the receiver is an instance of aClass or any of its subclasses.

For class-object receivers, follows Smalltalk semantics: self class is the metaclass, so the check walks the parallel metaclass hierarchy. The parallel chain is grounded at ProtoObject class superclass == Class (ADR 0036), so the metaclass tower merges into the instance-side Class → Behaviour → Object → ProtoObject chain. As a result, Integer isKindOf: Object and Integer isKindOf: Class both return true.

Examples

42 isKindOf: Integer        // => true
42 isKindOf: Object         // => true
#foo isKindOf: Symbol       // => true
#foo isKindOf: String       // => false
Integer isKindOf: Number    // => false (metaclass chain, not instance chain)
Integer isKindOf: Number class  // => true  (Number class is in the parallel chain)
Integer isKindOf: Object    // => true (grounded — Object is reachable via the metaclass tower)
Integer isKindOf: Class     // => true (Integer class inherits from Class)
error: message

Raise an error with the given message.

Examples

self error: "something went wrong"
delegate Sealed

Delegate message dispatch to the backing Erlang module (ADR 0101, BT-2720).

This method is a sentinel — a plain Object has no backing Erlang module, so calling delegate raises an Error at runtime. Stateless Objects declared with native: have their self delegate method bodies rewritten by the compiler's codegen phase to call the backing module directly, so the sentinel is never reached on a native: class.

Unlike Actor's delegate (visible only to Actor subclasses), this Object-base sentinel is visible to every class, so delegate is a reserved selector on the Object protocol.

Examples

42 delegate   // => ERROR: delegate called on a non-native Object

From ProtoObject

== other

Test value equality (Erlang ==, non-strict — 1 == 1.0 is true).

Examples

42 == 42           // => true
"abc" == "abc"     // => true
/= other

Test value inequality (negation of ==).

Examples

1 /= 2             // => true
42 /= 42           // => false
=:= other

Test strict value equality (Erlang =:= — 1 =:= 1.0 is false, unlike ==).

Every object supports this at runtime (it lowers directly to Erlang's =:= operator regardless of receiver type, ADR 0002) — declared here, once, so it is visible in method listings/completions/respondsTo: for every class, not just the handful (Integer, String, ...) that separately redeclare it with a narrower, class-typed other for documentation purposes.

Examples

1 =:= 1             // => true
1 =:= 1.0           // => false (strict — different types)
(Dictionary new) =:= #{}   // => true
=/= other

Test strict value inequality (negation of =:=).

Examples

1 =/= 1.0           // => true (strict — different types)
1 =/= 1             // => false
class

Return the class of the receiver.

Examples

42 class            // => Integer
"hello" class       // => String
doesNotUnderstand: selector args: arguments

Handle messages the receiver does not understand. Override for custom dispatch.

No declared return type (BT-2834 pattern, see Object>>fieldAt:): a custom override can return any type, and callers chain further sends on the result that a fixed -> Object would statically reject.

Examples

42 unknownMessage   // => ERROR: does_not_understand
perform: selector withArguments: arguments

Send a message dynamically with an arguments list.

Sent to a class, the class method runs in the caller's process, exactly as the same send written out would, for every selector that is not process-bound (new, spawn, startLink, ...; ADR 0142, ADR 0153).

Examples

42 perform: #abs withArguments: #()   // => 42
perform: selector withArguments: arguments timeout: timeoutMs

Send a message dynamically with an arguments list and explicit timeout.

The timeout (in milliseconds or #infinity) applies to the gen_server:call when the receiver is an actor. For value types, timeout is ignored.

Examples

actor perform: #query withArguments: #(sql) timeout: 30000