Scala class running a file chooser

2019-09-18 00:16发布

问题:

When I run this code in Scala it works well:

scala> import javax.swing.JFileChooser
scala> import java.io.File
scala> def run() {
    var chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
 }
scala> run()

However this code does not work and I'd like to understand why:

scala> class FileChoose {
  def run() {
    var chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}
defined class FileChoose

Here is the problem :

scala> new FileChoose.run()
<console>:13: error: not found: value FileChoose
              new FileChoose.run()
                  ^

回答1:

(new FileChoose).run()

Why it needs to be like that is clear if you consider the following example:

class Bar {
  def foo {}
}

object Bar {
  class foo
}

new Bar.foo
(new Bar).foo