Is there a built-in way to define fields/variables accepting values in a specific range? I mean a way of resolving it in compile-time.
For example, defining a double variable that only takes values between 1-10.
The closest you can get is
1) create an Enum for your range of values, that's what Enums are for.
public Enum MyVals {
ONE(1)
TWO(2)
...
private int val;
MyVals(int val) {
this.val = val;
}
}
see this. Of course this will only work if the values are discrete (i.e. not floats)
2) make the field private and write a smart setter that blows up on an unacceptable value.
public void setVal(int val) {
if (val < 0 || val > 10) throw....;
this.val = val;
}
Nope, since in compilation time there is no way to know if your software logic will produce values out of range. And in runtime there is no implementation for it supported by the native sdk. You can however wrap the type classes (e.g. Create class MyInteger
with an Integer
instance as a member wrapped by range verification methods in the MyInteger
class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With