Events Scala Swing事件中使用的反引号
我是Scala新手,下面的一个例子让Swing在Scala中工作,我有一个问题。基于Events Scala Swing事件中使用的反引号,events,swing,scala,Events,Swing,Scala,我是Scala新手,下面的一个例子让Swing在Scala中工作,我有一个问题。基于 listenTo(celsius, fahrenheit) reactions += { case EditDone(`fahrenheit`) => val f = Integer.parseInt(fahrenheit.text) celsius.text = ((f - 32) * 5 / 9).toString case Edi
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
}
为什么我必须在EditDone(`fahrenheit`)和EditDone(`celsius`)中使用反引号(`)来标识我的文本字段组件,例如fahrenheit
和celsius
?为什么我不能直接使用EditDone(华氏)
谢谢
从EditDone中提取一个值,并将其与现有局部变量华氏温度进行比较,同时
case EditDone(fahrenheit)
从EditDone中提取一个值,创建一个新的局部变量
fahrenheit
(从而隐藏现有变量),并将提取的值分配给新变量。这与模式匹配有关。如果在模式匹配中使用小写名称:
reactions += {
case EditDone(fahrenheit) => // ...
}
然后匹配的对象(本例中的事件)将与任何小部件上的任何EditDone
事件匹配。它将小部件的引用绑定到名称fahrenheit
。在这种情况下,fahrenheit
成为一个新值
但是,如果使用反勾号:
val fahrenheit = new TextField
...
reactions += {
case EditDone(`fahrenheit`) => // ...
}
然后,只有当EditDone
事件引用先前定义的值fahrenheit
引用的现有对象时,模式匹配才会成功
请注意,如果值fahrenheit
的名称是大写的,比如fahrenheit
,那么您就不必使用反勾号,这就好像您已经放置了它们一样。如果在范围中有要匹配的常量或对象,这将非常有用-这些常量或对象通常具有大写名称
val fahrenheit = new TextField
...
reactions += {
case EditDone(`fahrenheit`) => // ...
}