12 · Object-Oriented Programming
Expose a return capability
Use -> impl Store to expose the declared trait while keeping the concrete implementation private. The compiler checks one concrete return representation for the function. Callers can use the promised trait methods; hidden fields and additional methods remain unavailable. Call an opaque method directly; use || store.read(key) when a callback is needed. Extracting store.read without its receiver is rejected.
On this page
Use -> impl Store to expose the declared trait while keeping the concrete implementation private. The compiler checks one concrete return representation for the function. Callers can use the promised trait methods; hidden fields and additional methods remain unavailable. Call an opaque method directly; use || store.read(key) when a callback is needed. Extracting store.read without its receiver is rejected.
Complete example
Expose a return capability.
// A caller needs a settings store, without depending on its storage fields.
trait Store {
fn read(self, key: str) -> str?
}
struct MemoryStore {
theme: str,
revision: int,
}
impl Store for MemoryStore {
fn read(self, key: str) -> str? {
if key == "theme" { self.theme } else { nil }
}
}
impl MemoryStore {
fn generation(self) -> int = self.revision
}
fn settings() -> impl Store = MemoryStore { theme: "dark", revision: 2 }
let store = settings()
print("Theme: {store.read("theme") ?? "light"}")
print("Font: {store.read("font") ?? "system"}")
// The returned value exposes read; theme, revision and generation stay private.
Reference
zolo run examples/features/40-syntax-fourth/14-opaque-returns.zolo --no-cache
See also