Java Reference
In-Depth Information
Listing 13-12. JavaFX Property Pattern to Create New Properties in Java
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
public class Person {
private StringProperty name;
public void setName(String val) { nameProperty().set(val); }
public String getName() { return nameProperty().get(); }
public StringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
}
Direct access to the property is restricted to allow it to be lazily created on the first use. The initialization occurs in
the nameProperty method if it is null, and then the get and set simply delegate the call to the same named method on
the property.
In ScalaFX, you get the same benefits of lazy initialization in a single line, as shown in Listing 13-13.
Listing 13-13. Simplified JavaFX Property Pattern Adapted Using ScalaFX APIs
import scalafx.beans.property.StringProperty
class Person {
lazy val name = new StringProperty(this, "name")
// this is optional, but supports the object-literal construction pattern:
def name_=(v: String) {
name() = v
}
}
The first line that defines the property is sufficient to do everything that the preceding Java code does. Declaring
name as a val tells Scala that it is a constant variable. The lazy keyword that precedes the declaration indicates that
it should not be initialized until the first use. As a result, you can directly access this variable from user code and the
initialization logic is automatically invoked when needed.
scala supports three different types of variable definitions: val , var , and def . the var keyword behaves most
closely to what you are familiar with in Java, and defines a variable that can be modified in place. the val keyword,
which we used here, declares a constant variable, and is most similar to final variables in Java. the last keyword, def ,
declares an expression that is reevaluated each time it is called, so it behaves just like a method in Java.
Tip
The second definition of a name_= method is special syntax for overloading the assignment operator in Scala. This
is how the object-literal-like syntax we used earlier works; however, it is just a shortcut for accessing the property and
assigning the value. It also demonstrates the basic pattern for how properties are used in ScalaFX.
Table 13-1 compares all the different combinations of how you access and set properties in Java and ScalaFX.
 
 
Search WWH ::




Custom Search