Displaying time since last update of an item

I have two rules of thumb I use.

  1. Try it without the as and if it doesn’t work the first thing to add is the as. This is the easiest to describe and the easiest to implement but it doesn’t really answer your question, just provides a way to handle it.

  2. When the Rules DSL sees any line of code it tries to figure out what the best of the available types to use is. As it does this it goes from left to right. When you have a line like above though, it gets to SinceLastUpdate.state and up to that point it has no hint yet as to what that type should be, so it chooses its best guess which is probably Object. Now if the Rules DSL were really smart it would then move on to the + 5 and realize that it needs to go back and change to Number. Sadly the Rules DSL doesn’t appear to be that smart so it instead throws an error indicating that the type is wrong.

But sometimes it is smart enough to look ahead. For example, if(SinceLastUpdate.state > 5) will work. I suspect is that because we are dealing with a boolean operator it looks at that operator first. Based on the operator it knows that both sides of the > need to be Comparable. And since DecimalType and 5 are both Comparable it works without the as.

So, in practice, you need to use the as when there is not enough information prior to the call to .state when there is nothing prior to the call that tells the Rules DSL that it needs to use it as a Number (or a String, or whatever).

In practice I find this ambiguity is mainly a problem with Numbers and when building a String using an Item’s state. For example:

val msg = MyItem.state + " is the state!" // generates an error because nothing tells the Rules DSL up to the call to .state that it needs to be a String
val msg = MyItem.name + " is set to " + MyItem.state // works because MyItem.name is a String so the Rules DSL knows that we are building a String

The DPs are neither complete nor comprehensive. Just because there isn’t a DP for it yet doesn’t mean it is not a good approach. Your code looks short and concise so I wouldn’t worry too much about the DPs for this.

However…

This is where a couple of the DPs could be useful. See