String.split.get and Number

I have a problem when using [a string].split(“xx”).get(y) where y is a Number item

.item file

Number aNumberItem
String aStringItem


// rule running when 
   System started


rule aButtomRule
   aButtomItem received update
   logInfo("debugger output", "value: " + aStringItem.state.toString.split("_").get(aNumberItem.state))

from log

[ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'aButtomRule-1' failed: Could not invoke method: org.eclipse.xtext.xbase.lib.IntegerExtensions.operator_plus(int,byte) on instance: null in aButtomRule

Why can’t I use a Number item to get my segment of the string? and how do I solve this? I have tried multiple ways of trying to cast it as a string, or a string to a Number or and integer or to an integer, nothing seems to work -.-

Because you are working with Java Object under the covers. The result of the call to split() returns a Java List and get() on a List requires a primitive int.

The state of a Number Item is either going to be a DecimalType or it’s going to be a QuantityType. Let’s assume it’s a DecimalType. This Object (if it’s an Object, it’s not a primitive) can be any representable number including floats and integers. Obviously you can’t get the 2.567th element of a List, that makes no sense.

So you have a function, get() which requires an int and an Object that can represent any numerical value. You can’t just cast it, you have to transform it. Luckily in this case that’s easy. DecimalType inherits from java.lang.Number which happens to have an intValue() method which returns the Number as a primitive int.

Unfortunately Rules DSL sometimes fails to recognize the proper types of Item states. If aNumberItem.state.intValue() doesn’t work, you will have to cast the state of the Item. But you can cast it to Number: (aNumberItem.state as Number).intValue().

It get’s more complicated if the number has units but I don’t think that will be the case here.

(aNumberItem.state as Number).intValue() worked, thanks for the help and explanation :slight_smile: