Type checking for closures and map combinations for groovy dsl

Viewed 17

i am currently testing somethings from the groovy documentation. I have stumbled across this example for a dsl.

show = { println it }
square_root = { Math.sqrt(it) }

def please(action) {
  [the: { what ->
    [of: { n -> action(what(n)) }]
  }]
}

// equivalent to: please(show).the(square_root).of(100)
please show the square_root of 100

Is there a way to ensure the type at the "of" operation is for example an int with proper syntax highlighting?

If that's not possible, what are ways to build a sentence like dsl with proper type checking?

Thank you!

ztwjsk

1 Answers

By introducing an interface to use for the return type(s), you can provide the IDE with a path to infer each of the methods in your dsl.

interface I { J the(DoubleFunction what) }
interface J { double of(double x) }

def show = { println it }
def square_root = { Math.sqrt(it) }

I please(action) {
  [the: { what ->
    [of: { n -> action(what(n)) }]
  }]
}

// equivalent to: please(show).the(square_root).of(100)
please show the square_root of 100

demonstration of type inferencing

Related