Type not assigned for initialised variables

I noticed this little quirk when playing around with typeless variables.

I’m interested in how variables change type during assignments - oddly, the behaviour is different depending on whether the variable was initialised when declared.

    var t
    var Boolean b = true
    t = b // appears to assign value but not type
    logInfo(LogSubpackage, "b.class = '{}'", b.class) // logs class as 'class java.lang.Boolean'
    logInfo(LogSubpackage, "t.class = '{}'", t.class) // fails with an Error

In the example above, t.class fails with an error message ‘class’ is not a member of ‘null’

But, if you give the variable an initial value when declared:

    var t = 0
    var Boolean b = 1
    t = b // assigns value and type
    logInfo(LogSubpackage, "b.class = '{}'", b.class) // logs class as 'class java.lang.Boolean'
    logInfo(LogSubpackage, "t.class = '{}'", t.class) // Succeeds !

Causes the type to be assigned with the value and t.class logs ‘class java.lang.Boolean’.

Interestingly, in the first example no matter what you assign to the variable ‘t’, it always generates an error on the ‘class’ method. But if you assign any initial value (Decimal, bool, int, string…), the type is always transferred on assignment.

This site says var t is invalid.

And remember, you cannot use var to declare a variable without explicit initialization, hence the following:

var x;

is not allowed, since local variable declaration requires initialization on the right side.

from https://www.codejava.net/java-core/the-java-language/var-keyword-in-java

1 Like

I hadn’t read that before - thanks Bruce!

This article is a good deep dive as well.
https://developer.oracle.com/java/jdk-10-local-variable-type-inference.html

Pity Xtend doesn’t give a compile time error.

1 Like

It can’t. Xtend endeavors to be a loosely typed language. As such, it doesn’t know there is a problem until runtime.

To add complexity, Xtend is running on top of and has access to Java which is strongly typed.

The article Bruce found mainly applies to Java. In Xtend, var t is allowed. But because you didn’t give it a type, it’s going to treat t as type Object I think, though I’d love to see the error when you call t.class as that implies it’s not necessarily the case.

In Xtend, as with most loosely typed languages, type is not determined until you actually try to use the variable. This is why the type can be changed to a variable on assignment.

NOTE: when you define the types in Rules DSL, it greatly increases the parse time and if you use primitives it’s even worse. It is best practice to avoid specifying type except where absolutely necessary. The engine will automatically promote numbers to BigDecimal so when you have calculations or assign a number to a variable without specifying the type it will be converted to a BigDecimal.