LoginSignup
0
0

More than 3 years have passed since last update.

[Scala] シングルトンオブジェクトとコンパニオンオブジェクト

Posted at

シングルトンオブジェクトとコンパニオンオブジェクト

class で宣言したクラスの場合、そこから複数のインスタンスを生成することができますが、object で宣言されたクラスからは、ひとつのインスタンスしか生成することができません。これを シングルトンオブジェクト といいます。

特徴としては、

  1. classを定義するようにobjectを定義できる
  2. シングルトンオブジェクトとクラスが同じ名前で定義された時、そのクラスのコンパニオンオブジェクトと呼ぶ
  3. クラスとコンパニオンオブジェクトは、互いに非公開メンバーにアクセスできる

1.について、classの代わりにobjectと定義すればOK。

scala> object sample {
     |   val s: String = "This is object."
     |   println(s)
     | }
defined object sample

↑で、objectを定義して、呼べば"This is object."が出力される。

scala> sample
This is object.

2.について、例えば以下のclassを定義して、同じ名前のobjectを定義すればOK。

class smaple
object sample // class sample に対するコンパニオンオブジェクト

3.について、以下のようなclassとobjectを定義する。

scala> :paste
// Entering paste mode (ctrl-D to finish)

class info(val publicInfo: String, private val secretInfo: String)
object info {
  def showWeight = {
    val info = new info("height, 186", "Weight, 126")
    println(info.secretInfo)
  }
}

// Exiting paste mode, now interpreting.

defined class info
defined object info

class info には、非公開なフィールド(private val) secretInfo が含まれているが、定義したコンパニオンオブジェクトからアクセスしている。

確認

scala> info.showWeight
Weight, 126

参考

https://docs.scala-lang.org/ja/tour/singleton-objects.html
https://www.amazon.co.jp/dp/B01LYPRFI7/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0