Major Edit: Rewrote with the cleaner OH 2.3 syntax.
The example lambda on the OH 1 wiki is overly complex and as written will not work in OH 2. This quick example will show a super simple lambda example with copious notes.
Here is the code without comments. It takes in an Item, logs it’s state and returns a slightly modified version of the String logged.
val log= [ GenericItem s | logInfo("lambda", s.state.toString) s.state.toString + " logged" ] rule "Call Lambda" when // some trigger then val loggedStr = log.apply(MyItem) end
Now with explanation.
// Previous to OH 2.3 you had to import Functions or Procedures. You no longer need to import these. // A lambda is a global variable. I use a val to make it a constant since we are not going to // reassign it. // // A Lambda has a limitation of no more than 6 arguments. // // Lambdas have absolutely no context. Any other global vars or vals (including other lambdas) // must be passed in as an argument. Lambdas do have access to Actions and all your Items // though so those do not necessarily need to be passed in. // // In the below there is a function that takes one GenericItem as its argument. Unlike the wiki // example, there is no need to use the fully qualified class name and in fact, because all the // core classes have moved to the Eclipse SmartHome packages the code on the wiki will not // work in OH 2. // // Note that we are specifying the type. The Rules DSL will determine the type (Functions versus Procedures) // based on the value of the last line(s) executed (if the lambda has more than one last line they must // all return or be of the same type. If the type returned by the last line is void the lambda will be a // Procedure. val log = [ GenericItem s | // log the passed in Item's state. Note we did not have to pass in the logInfo Action logInfo("lambda", s.state.toString) // The result from the last line of the lambda will be returned. s.state.toString + " logged" ] // Some rule that uses the lambda. It isn't worth writing a lambda if you do not have more // than one rule the needs to call it. rule "Call Lambda" when // some trigger then // To call a lambda you use .apply and pass the arguments val loggedStr = log.apply(MyItem) end
For a potential alternative to lambdas in some circumstances see: