Scala swing GUI - 编译器指示我的反应块中的某些情况无法访问?

时间:2012-11-04 17:16:14

标签: swing scala user-interface

这是大量代码的摘录,为简洁起见,删除了非相关代码。我已经测试了下面的代码(作为新项目中的单个类),并验证了同样的问题仍然存在。所以我知道问题是特定于此处包含的代码。

object HumanGUI extends SimpleGUIApplication with Logs {

  PropertyConfigurator.configure("log4j.properties")

  def top = new MainFrame {
    title = "BJ GUI"

  val PlayPanel = new BoxPanel(Orientation.Vertical) {
    val hitButton = new Button("Hit")
    val stayButton = new Button("Stay")
    val doubleButton = new Button("Double")
    val quitButton = new Button("Quit")

    contents += hitButton
    contents += stayButton
    contents += doubleButton
    contents += quitButton

    listenTo(hitButton, stayButton, doubleButton, quitButton)
    reactions += {
      case ButtonClicked(hitButton) =>
        debug("Clicked Hit!")
      case ButtonClicked(stayButton) =>
        debug("Clicked Stay!")
      case ButtonClicked(doubleButton) =>
        debug("Clicked Double!")
      case ButtonClicked(quitButton) =>
        debug("Clicked Quit!")
    }

    contents = new BoxPanel(Orientation.Vertical) {
      contents += playPanel
    }
  }  

具体来说,编译器告诉我此块中的最后3个案例无法访问:

    listenTo(hitButton, stayButton, doubleButton, quitButton)
    reactions += {
      case ButtonClicked(hitButton) =>
        debug("Clicked Hit!")
      case ButtonClicked(stayButton) =>
        debug("Clicked Stay!")
      case ButtonClicked(doubleButton) =>
        debug("Clicked Double!")
      case ButtonClicked(quitButton) =>
        debug("Clicked Quit!")
    }

为什么会出现这种情况?

1 个答案:

答案 0 :(得分:2)

当模式匹配所有小写变量将绑定到在这种情况下匹配的内容时,如果要匹配模式匹配之外的变量,则必须使用`(后退):

listenTo(hitButton, stayButton, doubleButton, quitButton)
    reactions += {
      case ButtonClicked(`hitButton`) =>
        debug("Clicked Hit!")
      case ButtonClicked(`stayButton`) =>
        debug("Clicked Stay!")
      case ButtonClicked(`doubleButton`) =>
        debug("Clicked Double!")
      case ButtonClicked(`quitButton`) =>
        debug("Clicked Quit!")
    }