concept expression in category groovy

appears as: expressions, n expression, expression, The expression, expression
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

  • Operators, expressions, and assignments.
  • Figure 9.2. An AST for the expression 1 + 1

    But these simple scenarios don’t allow for any just-in-time provision of code, whether that’s through users entering expressions as they might into a graphing calculator or developers providing replacement scripts for just the bits of code that require frequent changes within a live system. As an idea of how widely used this kind of facility can be, consider Visual Basic (VB). We’re not in the business of judging its pros and cons, but it would be hard to deny that VB is popular and has been for a long time. Although many developers write whole applications in VB from scratch, far more use the capability of various products to embed pieces of VB code to customize behavior in ways the original developers may never have even considered.

    16.2. Evaluating expressions and scripts with GroovyShell

    The first Groovy API we’ll examine is GroovyShell. This is in many ways the simplest of the integration techniques, and if it covers your situation, it may well be all you need. With all the libraries in place, we’ll start dynamically evaluating expressions in a few simple lines of code. We’ll then move gradually into more complex scenarios, passing data between the calling code and the dynamically executing script, and then creating classes in the script for use outside. We examine different ways of executing scripts—precompiling them or executing them just once—and the different types of scripts that can be run. Finally, we look at ways you can tweak GroovyShell for more advanced uses. Don’t worry if it seems there’s a lot to learn—in simple situations, simple solutions often suffice. Also, much of the information presented here is relevant when looking at the other APIs Groovy provides.

    // normal use
    def    g1 =  "1 + 1 equals ${1 + 1}"
    assert g1 == '1 + 1 equals 2'
    assert g1 instanceof CharSequence
    assert g1 instanceof GString
    
    def x = 10
    
    def    g2 =  "$x"   // reference
    assert g2 == "10"
    
    def    g3 =  "${x}" // expression
    assert g3 == "10"
    
    // lazy evaluation with a writeable closure!
    def g4 = "${ -> x}" // closure
    x = 20              // value change after definition
    assert g4 == "20"   // lazy evaluation!