|
Spec-Zone .ru
спецификации, руководства, описания, API
|
The built-in isInitialized function takes a variable reference as its argument, and returns true if it has ever been set. Note that only explicit sets are considered, if the variable starts out with the default value of the type this is not considered being set. One typical usage is to set up uninitialized instance variables in the init block:
class Temperature {
var fahrenheit : Number;
var celcius : Number;
function show() { println( "Fahrenheit: {fahrenheit}, Celcius: {celcius}" ) }
init {
if (not isInitialized(fahrenheit)) {
fahrenheit = celcius * 9 / 5 + 32
} else {
celcius = (fahrenheit - 32) * 5 / 9
}
}
}
Temperature{fahrenheit: 98.6}.show();
Temperature{celcius: 100}.show();
This will print:
Fahrenheit: 98.6, Celcius: 37.0 Fahrenheit: 212.0, Celcius: 100.0
If update is wanted any time the set occurs, then isInitialized can be used in the onReplaceClause:
class Temperature {
var fahrenheit : Number on replace {
if (isInitialized(fahrenheit)) {
celcius = (fahrenheit - 32) * 5 / 9
}
}
var celcius : Number on replace {
if (isInitialized(celcius)) {
fahrenheit = celcius * 9 / 5 + 32
}
}
function show() { println( "Fahrenheit: {fahrenheit}, Celcius: {celcius}" ) }
}
Note the isInitialized prevents the update when the instance variables are initially set to the default value.