Backquote用于Scala Swing事件 [英] Backquote Used in Scala Swing Event

查看:99
本文介绍了Backquote用于Scala Swing事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触到Scala,并遵循一个例子来让Swing在Scala工作,而且我遇到了一个问题。基于,

  listenTo(摄氏,华氏)
反应+ = {
案例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)



谢谢

解决方案

这与模式匹配有关。如果您在模式匹配中使用小写名称:

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

然后匹配对象(在这种情况下的事件)将与任何小部件上的任何 EditDone 事件匹配。它将把小部件的引用绑定到名字 fahrenheit



但是,如果您使用反引号,则 c fahrenheit 将成为该案例的新值。 p>

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

那么模式匹配只有在code> EditDone 事件是指以前定义的值 fahrenheit 引用的现有对象。



请注意,如果值 fahrenheit 的名称是大写字母,例如 Fahrenheit ,那么你不会不得不使用反引号 - 就像你把它们一样。如果您有要匹配的范围中的常量或对象,则这是有用的 - 这些常量或对象通常具有大写名称。


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.

这篇关于Backquote用于Scala Swing事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆