Note that there are some explanatory texts on larger screens.

plurals
  1. POTracking method invocations in Groovy closure
    primarykey
    data
    text
    <p>I'm writing a small DSL for reactive evaluation, need help with metaprogramming in Groovy.</p> <p>Sample DSL code:</p> <pre><code>Signal&lt;Integer&gt; a = var(1) Signal&lt;Integer&gt; b = var(2) Signal&lt;Integer&gt; c = signal { a(it) + b(it) } </code></pre> <p>The 'var' function creates new <code>Signal</code> instance.</p> <p>The <code>signal</code> function needs a list of <code>Signal</code> instances inside the closure (references to <code>a</code> and <code>b</code> in example).</p> <p>Working implementation:</p> <pre><code>interface Signal&lt;T&gt; { T now() } Signal.metaClass.call = { dependencies -&gt; dependencies?.add(delegate) delegate.now() } def signal = { Closure&lt;?&gt; body -&gt; def dependencies = new HashSet&lt;&gt;() body.call(dependencies) createSignal(dependencies, body) } </code></pre> <p>Is there any way to awoit passing <code>it</code> variable, so sample looks like</p> <pre><code>Signal&lt;Integer&gt; a = var(1) Signal&lt;Integer&gt; b = var(2) Signal&lt;Integer&gt; c = signal { a() + b() } </code></pre> <p><strong>EDIT:</strong> Stub <code>Signal</code> implementation for testing:</p> <pre><code>class SignalStub&lt;T&gt; implements Signal&lt;T&gt; { T value Collection&lt;Signal&lt;?&gt;&gt; dependencies static def var(value) { new SignalStub&lt;&gt;(value: value, dependencies: [])} static def createSignal(deps, body) { new SignalStub&lt;Object&gt;(value: body.call(), dependencies: deps) } @Override T now() { return value } } </code></pre> <p>Test case for DSL:</p> <pre><code>def a = var(1) def b = var(2) def c = signal { a() + b() } assert c.now() == 3 assert c.dependencies.contains(a) assert c.dependencies.contains(b) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload