groovy789's blog

技術系備忘録φ(..)メモメモ

久々の更新・・・(´・ω・`)

scalaのクラス、補助コンストラクタのまとめ

/**
 * コンストラクタのテスト.
 */
object Construct {
  def main(args: Array[String]) {
    // エラー
    //val a1 = new A
    //assert(a1.a == 1)

    val a2 = new A(2)
    assert(a2.a == 2)

    val b1 = new B
    assert(b1.a == 1)

    val c1 = new C
    assert(c1.a == 1 && c1.b == 2)

    val c2 = new C(3)
    assert(c2.a == 3 && c2.b == 2)

    val c3 = new C(4,5)
    assert(c3.a == 4 && c3.b == 5)

    val d1 = new D
    assert(d1.a == 1)

    val d2 = new D(2)
    assert(d2.a == 2)
  }
}

/** 通常クラス. */
class A(_a: Int) {
  val a = _a
}

/** コンストラクタで変数も定義. */
class B(val a: Int) {
  // 補助コンストラクタ
  def this() = this(1)
}

/** 補助コンストラクタ. */
class C(val a: Int, val b : Int) {
  // 引数なし補助コンストラクタ
  def this() = this(1, 2)
  // 引数1つ補助コンストラクタ
  def this(aa: Int) = this(aa, 2)
}

/** デフォルト値. */
class D(val a: Int = 1)