I am new to Scala and following one of the examples to get Swing working in Scala and I hava a question. Based on,
listenTo(celsius, fahrenheit)
reactions += {
case EditDone(`fahrenheit`) =>
val f = Integer.parseInt(fahrenheit.text)
celsius.text = ((f - 32) * 5 / 9).toString
case EditDone(`celsius`) =>
val c = Integer.parseInt(celsius.text)
fahrenheit.text = ((c * 9) / 5 + 32).toString
}
why do I have to use backquote (`) in EditDone(`fahrenheit`) and EditDone(`celsius`) to identify my textfield components e.g. fahrenheit
and celsius
? Why can't I just use EditDone(fahrenheit)
instead?
Thanks
This has to do with pattern matching. If you use a lower-case name within a pattern match:
reactions += {
case EditDone(fahrenheit) => // ...
}
then the object being matched (the event in this case) will be matched against any EditDone
event on any widget. It will bind the reference to the widget to the name fahrenheit
. The fahrenheit
becomes a new value in the scope of that case.
However, if you use backticks:
val fahrenheit = new TextField
...
reactions += {
case EditDone(`fahrenheit`) => // ...
}
then the pattern match will only succeed if the EditDone
event refers to the existing object referenced by the value fahrenheit
, defined previously.
Note that if the name of the value fahrenheit
were uppercase, like Fahrenheit
, then you wouldn't have to use backticks - it would be as if you've put them. This is useful if you have constants or objects in scope that you want to match against - these usually have uppercase names.
case EditDone(`fahrenheit`)
extracts a value from EditDone and compares it to the existing local variable fahrenheit
, while
case EditDone(fahrenheit)
extracts a value from EditDone, creates a new local variable fahrenheit
(thereby shadowing the existing one) and assigns the extracted value to the new variable.
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