Kind of an oxymoron. A constant should be .. well .. constant.
However there are times you want that constant to be permanent, or constant, and unchangeable but it needs to be computed at compile time.
And it turns out that in Xojo you can do that IF you define a constant in code like :
Const foo = 123 Const bar = 345 Const foobar = foo + bar
If you assigned these constants to variables so you could inspect them like
Dim iFoo As Integer = foo Dim iBar As Integer = bar Dim iFooBar As Integer = foobar break
you would see that iFoo, iBar and iFooBar have the values 123, 345, and 468 as expected. So constants can be formed from other constants and literals at compile time and they are then permanent in your application.
But you cannot do this in a constant defined using the IDE’s constant editor. It does not compute the values in the same way as it does when you define the value in code as shown above.
If you try to define constants, cFoo = 123, cBar = 345 and cFooBar = cFoo + cBar you will find that cFoo and cBar are ok and are numeric. But cFooBar will not compile if you set its type to Number. The usual trick of using #ConstantName which works in other places in the IDE wont work in the default value field of a Const defined this way. This has lead me to submit a bug report.
In the mean time whats a person to do ?
As it sits right now the BEST we can do is a workaround.
Constant-ness is a behavioural thing in most respects. Basically its a value that never changes. Like the value of Pi, Avogadro’s number, or the gravitational constant. In our code we would like a value that never chnages once it’s compiled for these sorts of values.
But if its one of our own making using an expression that is computed at compile time would be really nice. Something like bit flags for error conditions is a common use.
It might be that we have
Const Error = 1 Const IsFatal = 2 Const FatalError = Error + isFatal
And so we can see that a fatal error is computed from the Error & isFatal flags.
Currently the only way to provide a computed constant, or something that behaves like it, is a Computed Property that only has its getter implemented.
We could then have
ComputedProperty FatalError as Integer Get return Fatal + IsError End Get Set End Set End ComputedProperty
Semantically this would behave like a const.
The downside is that
- every time it’s accessed the value is recomputed (this can be worked around somewhat)
- every time it’s accessed there is method call overhead
While not a perfect replacement for a constant it’s what is possible today.