0

私は Java のバックグラウンドを持っていますが、予想どおり、Scala で使用されるいくつかのパターンを理解するのに問題があります (以下を参照)。Scala のパターンやプログラミングの方法論をよく理解していると感じるたびに、プログラミングの理解を超えた何かが浮かび上がり、学習モードに戻ります。これは、学び続けることを常に刺激する scala の美しさだと思います :)

とにかく、scala swing でサンプル プログラミングをしようとしています........

val frame = new MainFrame {
title = "Electronic Classroom"
contents = new BorderPanel {
  layout += new GridPanel(1, 2) {

    contents += new ScrollPane(semesterList)
    contents += new ScrollPane(courseList)
  } -> West

}

menuBar = new MenuBar {
  contents += new Menu("File") {

    contents += new MenuItem("Login") {
      action = Action("Login"){
          login
            user match{
          case Some(inst:Instructor) => instructorMenu.enabled = true
           enabled = false
           case Some(_) => instructorMenu.enabled = false
             enabled = false
          case _ =>
        }
      }

    }
    contents += new Separator
    contents += new MenuItem(Action("Exit")(sys.exit(0)))
  }
        }
  contents += instructorMenu
}

size = new Dimension(1000, 600)
centerOnScreen
 }

ここでは、値を定義する際に def または val キーワードを使用せずに def および val に値を設定しています (タイトル、サイズ、コンテンツなど)。すべての割り当てが Java で行う方法とは異なり、ボディ スクリプトのように見えます。などはメソッド本体で行われます..ここに大きなデザインパターンが欠けていると思います

誰か助けて、Scalaのデザインパターンを説明してくれませんか??

4

2 に答える 2

1

This is actually not very different from Java—instead of creating an instance and then customising it, you are creating anonymous sub classes. E.g.

val frame = new MainFrame {
  title = "Electronic Classroom"
}

instead of

val frame = new MainFrame
frame.title = "Electronic Classroom"

The difference to Java is that since Scala doesn't have dedicated constructor methods but treats all expressions within the body of a class part of the constructor, your anonymous sub class kind of "overrides" the constructor.

To compare directly with Java, lets say it wasn't anonymous:

class MyMainFrame extends MainFrame {
  title = "Electronic Classroom"
}

In Java, this would be roughly equivalent to:

public class MyMainFrame extends JFrame {
    public MyMainFrame() {
        super();
        setTitle("Electronic Classroom");
    }
}

(I hope this is valid Java syntax, I'm a bit rusty)


This is the same case for MenuBar, Menu, MenuItem. Only Action { ... } is not subclassing but calling method apply on the Action companion object, making the syntax a bit more succinct (this way you won't have "constructor" statements, e.g. you couldn't write accelerator = None and so forth).

于 2013-08-14T20:31:50.177 に答える
0

I subscribe to 0__'s explanation, just wanting to add that if I recall correctly you can do the same in java with

JFrame frame = new JFrame {{
    title = "Electronic Classroom";
}};

This should create an anonymous subclass with the additional code appended to the constructor

于 2013-08-14T22:07:24.587 に答える