Method & assignment cascades for Nim, inspired by Smalltalk & Dart.
cascade is a macro for Nim that implements method cascades, a feature originally from Smalltalk that's made its way into modern languages like Dart and Kotlin.
It allows you to avoid repeating an object's name for each method call or assignment. A common case is something like a button:
# before
var res = Button()
res.text = "ok"
res.width = 30
res.color = "#13a89e"
res.enable()With cascade, you don't need to repeat yourself:
# after
let btn = cascade Button():
text = "ok"
width = 30
color = "#13a89e"
enable()Also notice you can avoid declaring a var if you don't need to modify
the target object after the fact — the object is mutable within the
cascade block but becomes a let binding outside of that block.
Install using Nimble:
nimble install cascadeThen import and use:
import cascade
let x = cascade y:
z = 10
f()-
field assignment
let foo = cascade Foo(): bar = 100 # ↑ equivalent ↓ var foo = Foo() foo.bar = 100
-
nested field assignment
let foo = cascade Foo(): bar.baz.qux = "awesome" # ↑ equivalent ↓ var foo = Foo() foo.bar.baz.qux = "awesome"
-
proc/template/method calls
let foo = cascade Foo(): fn("hello", "world") # ↑ equivalent ↓ var foo = Foo() foo.fn("hello", "world")
-
nested calls on fields
let foo = cascade Foo(): bar.baz.seqOfStrings.add "more awesome" # ↑ equivalent ↓ var foo = Foo() foo.bar.baz.seqOfStrings.add "more awesome"
-
ifandwhenconditionalslet foo = cascade Foo(): if someCondition: bar.baz = 2 # ↑ equivalent ↓ var foo = Foo() if someCondition: foo.bar.baz = 2
-
cascades can be nested within each otherlet foo = cascade Foo(): bar = cascade Bar(): baz = cascade Baz(): str = "we're down here now!" # ↑ equivalent ↓ var foo = Foo() foo.bar = Bar() foo.bar.baz = Baz(str: "we're down here now!")
Is something missing? Check the open issues first or open a new one. Pull requests are appreciated!
To build cascade from source you'll need to have Nim installed, and should also have Nimble, Nim's package manager.
- Clone the repo:
git clone https://github.com/haltcase/cascade.git - Move into the newly cloned directory:
cd cascade - Make your changes:
cascade.nim,tests/tests.nim - Run tests:
nimble test
You can check the issues for anything unresolved, search for a problem you're encountering, or open a new one. Pull requests for improvements are also welcome.
MIT © Bo Lingen / haltcase