Java Reference
In-Depth Information
Every time that x is modified, it will run the block of code specified by the on
replace phrase, essentially keeping y in lock step with x . However, there is one
fundamental difference between the two solutions. Recall that earlier in this chap-
ter it was shown that it is illegal to reassign bound variables by default, and with
our trigger example, for better or worse, that restriction is removed. For example:
class Lyric {
public var phrase : String on replace {
s = phrase;
}
}
var l = Lyric { phrase: "so long" };
var s : String;
println("phrase={l.phrase}, s={s}");
l.phrase = "farewell";
println("phrase={l.phrase}, s={s}");
// would be illegal if s = bind l.phrase
s = "auf Wiedersehen";
println("phrase={l.phrase}, s={s}");
l.phrase = "farewell";
println("phrase={l.phrase}, s={s}");
l.phrase = "good night";
println("phrase={l.phrase}, s={s}");
prints out:
phrase=so long, s=
phrase=farewell, s=farewell
phrase=farewell, s=auf Wiedersehen
phrase=farewell, s=auf Wiedersehen
phrase=good night, s=good night
Among others, a few important things to point out here are
1. Even though the variable s is reassigned every time l.phrase changes,
the first line of output shows that they are different. Why? Because l is
declared and instantiated first. At the time of instantiation, l is modified,
but the trigger can't update s , because s hasn't been defined yet.
2. The variable s can be reassigned, temporarily un-synchronizing it from
l.phrase .
3. The on replace block will not be executed until the value of the phrase
instance variable changes, regardless of whether it subsequently appears
on the left hand side of an assignment statement. This is evidenced by the
fact that the second assignment of l.phrase="farewell" does not cause
s to be resynchronized with l.phrase .
Search WWH ::




Custom Search