String Question - Lazy evaluation of Strings

I'm trying to use Lazy String evaluation as explained in, e.g., Section 7 of this article https://www.baeldung.com/groovy-closures

As I understand it, the following code should be valid:

void stringTest() {
	int  thisNumber = 5
    def myString = "This Number is ${ -> thisNumber}"
	log.debug myString
}

I have this in a simple driver file. When It try to save the code in Hubitat, I get the error:

Anybody know why? Is this type of function blocked in Hubitat, or have I done something wrong in the code?

Change it to

def myString = "This Number is ${thisNumber}"

Thanks for the response. I'm aware of the usage you mentioned. However, the usage I'm going for is different -- adding "->" within the closure is supposed to change the timing of the variable evaluation.

With mystring as you've defined it, if you have code

number = 3
def myString = "This Number is ${thisNumber}"
log.debug myString
number = 4
log.debug myString

The result would be

This Number is 3
This Number is 3

because "thisNumber" is defined at the time the string is defined.
If you have
With the "->" in the closure, the evaulation of "thisNumber" becomes "lazy" and doesn't happen until the string is evaluated, so the result should be

This Number is 3
This Number is 4

I'm asking because, with the new "libraries" function coming in 2.2.8, I want to define some strings in libraries and want the evaluation of the parameters to be "lazy" so the full string changes as certain variables change.

What I was trying to figure out is, (i) Maybe this is a groovy 2.2.5 or later feature, or (ii) its been somehow disabled for hubitat (possibly unintentionally), or (iii) I'm using it wrong.

thanks.

1 Like

Ahhh, gotcha! Maybe a question for @gopher.ny, then.

I'd say that theoretically it should work..

Work around perhaps:

void stringTest() {
	int  thisNumber = 5
    def myStringClosure = {"This Number is ${thisNumber}"}
	log.debug myStringClosure()
    
    thisNumber = 6
    log.debug myStringClosure()
}

Libraries act as includes/way to reduce code duplication. It is literally string substitution. If it works in plain code, it will work exactly the same way if put into a library.

Not sure about the origins of this exception other than it comes from Groovy parser.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.