【Scala】classとobject
Scalaのclassとobjectの違いだが、classはいわゆるJavaでいうところのクラスと同じ。
ただ、Scalaのクラスではstaticな変数やメソッドを定義することが出来ない。
その代わりに、object(シングルトン)を使う。
class
Scalaのクラス定義
class Foo {} // インスタンス生成 scala> new Foo res5: Foo = Foo@1e28a31b
クラス定義と同時にコンストラクタを定義
class Foo(x: Int, y:Int) { def add() = x + y } scala> new Foo(1, 2).add() res7: Int = 3
この場合、xとyはクラス内でのみ使用可能。
var,valを使って宣言するとフィールドになる
class Foo(var x: Int, val y: Int) {} scala> val foo = new Foo(1, 2) foo: Foo = Foo@2b529fb7 scala> foo.x res10: Int = 1 scala> foo.y res11: Int = 2
コンストラクタのオーバーロード
class Foo(x: Int, y: Int) { def this(x: Int, y: Int, z: String) { // 呼び出さないといけない this(x, y) println(z) } } scala> new Foo(1, 2, "foo text") foo text res15: Foo = Foo@5f02f3f7
object
オブジェクト定義
object Foo {} scala> Foo res0: Foo.type = Foo$@44fc511a
オブジェクトの変数やメソッドへのアクセス
object Foo { val x = 1 val y = 2 def add() = x + y } scala> Foo.x res1: Int = 1 scala> Foo.y res2: Int = 2 scala> Foo.add() res3: Int = 3