Backquote Used in Scala Swing Event

I am new to Scala and follow one example to get Swing to work in Scala and I have a question. Based,

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 need to use backquote (`) in EditDone (` fahrenheit`) and EditDone (`celsius`) to identify my text field components, for example. fahrenheit and celsius ? Why can't I use EditDone(fahrenheit) instead?

thanks

+7
source share
2 answers

This is due to pattern matching. If you use a lowercase name according to the pattern:

 reactions += { case EditDone(fahrenheit) => // ... } 

then the object being mapped (an event in this case) will be mapped to any EditDone event for any widget. It will link the widget link to fahrenheit . fahrenheit becomes a new value in the scope of this event.

However, if you use backlinks:

 val fahrenheit = new TextField ... reactions += { case EditDone(`fahrenheit`) => // ... } 

then matching the pattern will succeed only if the EditDone event refers to an existing object referenced by the fahrenheit value defined earlier.

Note that if the name of the fahrenheit value was uppercase, for example fahrenheit , then you would not have to use backreferences - it would be as if you put them. This is useful if you have constants or objects in the area that you want to map to - they usually have upper case names.

+15
source
 case EditDone(`fahrenheit`) 

extracts the value from EditDone and compares it with the existing local variable fahrenheit , and

 case EditDone(fahrenheit) 

extracts a value from EditDone, creates a new local fahrenheit variable (thereby obscuring the existing one) and assigning the extracted value to a new variable.

+8
source

All Articles