2

How to create a closure from a string?

Like I have a string def formula = "{it * it}"

Now formula is a string and I can't do formula()

how do I define the code block in the string variable formula as a closure?

user1076371
  • 161
  • 6

1 Answers1

2

You can do:

def formula = Eval.me( "{ x -> x * x}" )

formula( 3 )

Obviously the usual warnings about the safety of evaluating strings entered by users apply

You might also be interested in a nearly identical question that was asked yesterday

Community
  • 1
  • 1
tim_yates
  • 167,322
  • 27
  • 342
  • 338