我是Scala的新手,并按照其中一个示例让Swing在Scala中工作,我有一个问题。基于,
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(fahrenheit)
?
由于
答案 0 :(得分:15)
这与模式匹配有关。如果在模式匹配中使用小写名称:
reactions += {
case EditDone(fahrenheit) => // ...
}
然后匹配的对象(在这种情况下为事件)将与任何小部件上的任何EditDone
事件匹配。它会将对窗口小部件的引用绑定到名称fahrenheit
。 fahrenheit
成为该案例范围内的新值。
但是,如果你使用反引号:
val fahrenheit = new TextField
...
reactions += {
case EditDone(`fahrenheit`) => // ...
}
然后只有当EditDone
事件引用之前定义的值fahrenheit
引用的现有对象时,模式匹配才会成功。
请注意,如果值fahrenheit
的名称是大写的,例如Fahrenheit
,那么您就不必使用反引号 - 就像您已经放置它们一样。如果要在范围中包含要匹配的常量或对象,这将非常有用 - 这些常量或对象通常具有大写名称。
答案 1 :(得分:8)
case EditDone(`fahrenheit`)
从EditDone中提取值并将其与现有的局部变量fahrenheit
进行比较,而
case EditDone(fahrenheit)
从EditDone中提取值,创建一个新的局部变量fahrenheit
(从而遮蔽现有变量)并将提取的值分配给新变量。