Making OH Rules Easier for Everyone

Thanks for a great post that levelled up my understanding of lambdas. One question: what about that lambda causes the return value to be 6? In C[++] terms I’d expect a ”return” keyword but I don’t see something similar there, only that “bar” is having 1 added to it.

The result of the last line in the lambda gets returned. If that last line returns void then the lambda becomes a Procedure instead of a Function.

So in the above case, the last line executed is bar + 1 so that is what gets returned. And it should infer the type (i.e. Number) for the return based on context.

Usually it is easy to tell what the last line executed is since it is the literal last line of the lambda. But if you did something like the following you would get an error (usually something mentioning how there is no side effect):

val myLambda = [ String foo, Number bar |
    if(bar == 0) logInfo("test", "Foo = " foo)
    else bar + 1
]

In this case the last line executed is dependent on the value of bar. If bar is 0 then a void is returned (logInfo returns void) else bar + 1 gets returned. Since the types of the two returns differ the parser will complain and say it’s an invalid lambda. To correct the above you can do something like:

val myLambda = [ String foo, Number bar |
    if(bar == 0) {
        logInfo("test", "Foo = " foo)
        -1
    }
    else bar + 1
]

This works because in the case where bar is 0 the last line executed is -1 so a -1 gets returned. And -1 is the same type as bar + 1 so everything is good.

1 Like