0

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

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!")
    }

为什么会这样?

4

1 回答 1

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!")
    }
于 2012-11-04T17:23:19.867 回答